Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove key from all objects in array

I have the following array of objects:

[{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"...}]

I want to filter the object array and keep only two keys, id and value to get something like this:

[{id:1, value:"100"},
{id:2, value:"200"},
{id:3, value:"300"},
{id:4, value:"400"},
{id:5, value:"500"}]

Currently, I'm traversing through the object array with a for loop and doing a push() to an empty array with the new variables. Is there an easier way to do this?

I wanted to use Lodash like _.pluck(PetList, 'id', 'value'); but lodash extracts the value only, not the key.

like image 876
lost9123193 Avatar asked Jun 03 '17 21:06

lost9123193


People also ask

How do you remove all objects from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do I remove an object using the key?

Use delete to Remove Object Keys The special JavaScript keyword delete is used to remove object keys (also called object properties). While you might think setting an object key equal to undefined would delete it, since undefined is the value that object keys that have not yet been set have, the key would still exist.

Can you remove items from an array?

If you want to remove an item from an array, you can use the pop() method to remove the last element or the shift() method to remove the first element. However, if the item you want to remove is not the first or last element, these methods are not the tools for the job.


1 Answers

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.

like image 157
Andrew Li Avatar answered Sep 28 '22 08:09

Andrew Li