-2
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.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212

2 Answers2

2

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.

stukilgore
  • 101
  • 3
0

Use .map on the array and inside the callback delete the key age.

var data = {
  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",
    }
  ]
};

var newData = data.people.map(el => { delete el.age; return el; });

console.log(newData);
void
  • 36,090
  • 8
  • 62
  • 107