Search code examples
javascriptarraysjavascript-objects

Returning an Array of Objects.... from an Array of Objects


people: [
  {
    name: "Jon Doe",
    age: "25",
    city: "Detroit",
  },
  {
    name: "Jane Doe",
    age: "23",
    city: "Detroit",
  },
  {
    name: "Jack Doe",
    age: "22",
    city: "Detroit",
  },
  {
    name: "Joe Doe",
    age: "28",
    city: "Detroit",
  },
  {
    name: "Josh Doe",
    age: "27",
    city: "Detroit",
  }
]

TO THIS ------------>

anotherArray: [
  {
    name: "Jon Doe",
    city: "Detroit"
  },
  {
    name: "Jane Doe",
    city: "Detroit"
  },
  {
    name: "Jack Doe",
    city: "Detroit"
  },
  {
    name: "Joe Doe",
    city: "Detroit"
  },
  {
    name: "Josh Doe",
    city: "Detroit"
  }
]

How would I achieve this result? I just want to pull certain keys from each object, then make an object of those selected keys. Intuitively, I am thinking maybe the .map method but so far each attempt has been a failure.

NOTE: There is a similar question How to remove properties from an object array?. This is not a duplicate question, because I am not trying to DELETE anything from the object, and I attempting to create a new object with specific results.


Solution

  • I'd recommend using .map :

    //Using your above people array:
    
    people.map( ({name, city}) => ({name, city}) )
    

    This should return the array you're looking for.