从数组中的所有对象中删除键 [英] Remove key from all objects in 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"...}]
我想过滤对象数组并只保留两个键,id
和 value
以获得如下内容:
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"}]
目前,我正在使用 for 循环遍历对象数组,并对带有新变量的空数组执行 push()
操作.有没有更简单的方法来做到这一点?
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?
我想像 _.pluck(PetList, 'id', 'value');
一样使用 Lodash,但 lodash 只提取值,而不是键.
I wanted to use Lodash like _.pluck(PetList, 'id', 'value');
but lodash extracts the value only, not the key.
推荐答案
Array#filter
从数组中过滤单个项目,而不是数组中某个对象的某些键.您可以使用方法 Array#map
转换对象,只保留你想要的键.map
旨在将数组的每个元素转换为新值,将旧值映射"为新值:
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
}));
以上遍历数组,将当前对象存入pet
.然后它从 箭头函数 这将是 newPetList
中相应的转换对象,只有来自 pet
的键 id
和 value
.结果是旧数组中的所有对象都映射到一个没有name
键的新对象.
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);
这将 name
属性绑定到 name
并将其余部分保留在 rest
中,您可以返回以删除 name
键.
This binds the name
property to name
and keeps the rest in rest
, which you can return to remove the name
key.
这篇关于从数组中的所有对象中删除键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!