Remove key from all objects in array
What you are trying to achieve is called mapping rather filtering. Here's a solution
var array = [{id:1, value:"100", name:"dog"},
{id:2, value:"200", name:"cat"},
{id:3, value:"300", name:"fish"},
{id:4, value:"400", name:"mouse"},
{id:5, value:"500", name:"snake"}];
var result = array.map(function(obj) {
return {id: obj.id, value: obj.value};
});
console.log(result);
Array#filter
filters individual items out of the array, not certain keys from an object in the array. You could use the method Array#map
to transform the objects and only keeping the keys you want. map
is designed to transform each element of an array to something new, "mapping" the old value to a new value:
let newPetList = PetList.map(pet => ({
id: pet.id,
value: pet.value
}));
The above traverses the array, and stores the current object in pet
. It then returns a new object from an arrow function which will be the corresponding transformed object in newPetList
with only keys id
and value
from pet
. The result is that all objects in the old array are mapped to a new object with no name
key.
You could also, with object destructuring, filter put unwanted properties like so:
let newPetList = petList.map(({ name, ...rest }) => rest);
This binds the name
property to name
and keeps the rest in rest
, which you can return to remove the name
key.