从数组中的所有对象中删除键 [英] 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?
我想使用Lodash,如 _。pluck(PetList,'id','value') ;
但是lodash仅提取值,而不是密钥。
I wanted to use Lodash like _.pluck(PetList, 'id', 'value');
but lodash extracts the value only, not the key.
推荐答案
数组#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
中相应的转换对象,只有 id
和值
来自 pet
。结果是旧数组中的所有对象都映射到一个没有 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.
这篇关于从数组中的所有对象中删除键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!