问题描述
我有一个看起来像这样的对象数组:
I have an array of objects that looks like this:
var array = [
{id:123, value:"value1", name:"Name1"},
{id:124, value:"value2", name:"Name1"},
{id:125, value:"value3", name:"Name2"},
{id:126, value:"value4", name:"Name2"}
...
];
如您所见,有些名称是重复的.我想获得一个只有名称的新数组,但如果某些名称重复,我不想再次添加它.我想要这个数组:
As you can see, some names are repeated. I want to get a new array with names only, but if some name repeats I don't want to add it again. I want this array:
var newArray = ["Name1", "Name2"];
我正在尝试使用 map
来做到这一点:
I'm trying to do this with map
:
var newArray = array.map((a) => {
return a.name;
});
但问题是这会返回:
newArray = ["Name1", "Name1", "Name2", "Name2"];
如何在 map
中设置一些条件,使其不返回已存在的元素?我想用 map
或其他一些 ECMAScript 5 或 ECMAScript 6 功能来做到这一点.
How can I set some condition inside map
, so it won't return an element that already exists? I want to do this with map
or some other ECMAScript 5 or ECMAScript 6 feature.
推荐答案
使用 ES6,你可以使用 Set
用于唯一值,仅映射对象的名称后.
With ES6, you could use Set
for unique values, after mapping only the names of the objects.
该提案使用传播语法...
用于收集新数组中的项目.
This proposal uses a spread syntax ...
for collecting the items in a new array.
const array = [{ id: 123, value: "value1", name:"Name1" }, { id: 124, value: "value2", name: "Name1" }, { id: 125, value: "value3", name: "Name2" }, { id: 126, value: "value4", name: "Name2" }],
names = [...new Set(array.map(a => a.name))];
console.log(names);
这篇关于从数组中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!