ES6 - 从对象数组中删除重复项 [英] ES6 - Removing duplicates from array of objects

查看:23
本文介绍了ES6 - 从对象数组中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个对象数组如下:

const listOfTags = [{id:1,标签:你好",颜色:红色",排序:0},{id:2,标签:世界",颜色:绿色",排序:1},{id:3,标签:你好",颜色:蓝色",排序:4},{id:4,标签:阳光",颜色:黄色",排序:5},{id:5,标签:你好",颜色:红色",排序:6},]

如果标签和颜色相同,则会出现重复条目​​.在这种情况下,id = 1 和 id = 5 的对象是重复的.

如何过滤此数组并删除重复项?

我知道您可以通过以下方式过滤一个键的解决方案:

const unique = [... new Set(listOfTags.map(tag => tag.label)]

但是多个键呢?

根据评论中的要求,这里是期望的结果:

<预><代码>[{id:1,标签:你好",颜色:红色",排序:0},{id:2,标签:世界",颜色:绿色",排序:1},{id:3,标签:你好",颜色:蓝色",排序:4},{id:4,标签:阳光",颜色:黄色",排序:5},]

解决方案

您可以在闭包中使用 Set 进行过滤.

constlistOfTags = [{ id: 1, label: "Hello", color: "red", sort: 0 }, { id: 2, label: "World", color: "green", sort: 1 }, { id:3、标签:你好",颜色:蓝色",排序:4},{id:4,标签:阳光",颜色:黄色",排序:5},{id:5,标签:你好", 颜色: "红色", 排序: 6 }],键 = ['标签','颜色'],过滤 = listOfTags.filter((s => o =>(k => !s.has(k) &&s.add(k))(keys.map(k => o[k]).join('|')))(新套装));console.log(filtered);

.as-console-wrapper { max-height: 100% !important;顶部:0;}

Assuming an array of objects as follows:

const listOfTags = [
    {id: 1, label: "Hello", color: "red", sorting: 0},
    {id: 2, label: "World", color: "green", sorting: 1},
    {id: 3, label: "Hello", color: "blue", sorting: 4},
    {id: 4, label: "Sunshine", color: "yellow", sorting: 5},
    {id: 5, label: "Hello", color: "red", sorting: 6},
]

A duplicate entry would be if label and color are the same. In this case Objects with id = 1 and id = 5 are duplicates.

How can I filter this array and remove duplicates?

I know solutions where you can filter against one key with something like:

const unique = [... new Set(listOfTags.map(tag => tag.label)]

But what about multiple keys?

As per request in comment, here the desired result:

[
    {id: 1, label: "Hello", color: "red", sorting: 0},
    {id: 2, label: "World", color: "green", sorting: 1},
    {id: 3, label: "Hello", color: "blue", sorting: 4},
    {id: 4, label: "Sunshine", color: "yellow", sorting: 5},
]

解决方案

You could use a Set in a closure for filtering.

const
    listOfTags = [{ id: 1, label: "Hello", color: "red", sorting: 0 }, { id: 2, label: "World", color: "green", sorting: 1 }, { id: 3, label: "Hello", color: "blue", sorting: 4 }, { id: 4, label: "Sunshine", color: "yellow", sorting: 5 }, { id: 5, label: "Hello", color: "red", sorting: 6 }],
    keys = ['label', 'color'],
    filtered = listOfTags.filter(
        (s => o => 
            (k => !s.has(k) && s.add(k))
            (keys.map(k => o[k]).join('|'))
        )
        (new Set)
    );

console.log(filtered);

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于ES6 - 从对象数组中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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