如果元素中已存在元素,请不要再次添加 [英] If an element already exists in an array, don't add it again

查看:131
本文介绍了如果元素中已存在元素,请不要再次添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的对象数组:

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

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,您可以使用仅映射对象名称后,设置 的唯一值。

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);

这篇关于如果元素中已存在元素,请不要再次添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆