Home > other >  Filter multiple specific properties from an array of objects into a new array
Filter multiple specific properties from an array of objects into a new array

Time:11-22

I have a big array of objects such as

let arr = [
  {name: "name1" , surname: "surname1", age: "22"},
  {name: "name2" , surname: "surname2", age: "23"},
  {name: "name3" , surname: "surname3", age: "24"},
]

But i need to filter it so it will be

arr = [
  {name: "name1" , surname: "surname1"},
  {name: "name2" , surname: "surname2"},
  {name: "name3" , surname: "surname3"},
]

How can i do so?

CodePudding user response:

Using Array#map:

const arr = [ {name: "name1" , surname: "surname1", age: "22"}, {name: "name2" , surname: "surname2", age: "23"}, {name: "name3" , surname: "surname3", age: "24"} ];

const res = arr.map(({ name, surname }) => ({ name, surname }));

console.log(res)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Given that you want to filter multiple properties, you can store the properties to delete inside an array, then loop through it when maping and delete the properties:

const propertiesToFilter = ['age']

let arr = [
{name: "name1" , surname: "surname1", age: "22"},
{name: "name2" , surname: "surname2", age: "23"},
{name: "name3" , surname: "surname3", age: "24"},
]

const res = arr.map(e => (propertiesToFilter.forEach(f => delete e[f]), e))

console.log(res)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Using simple for-of with object-destructuring

for(person of arr){
    const {name, surname} = person;
    res.push({name, surname})
}
  • Related