Lodash从数组中删除重复项 [英] Lodash remove duplicates from array

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

问题描述

这是我的数据:

[
    {
        url: 'www.example.com/hello',
        id: "22"    
    },
    {
        url: 'www.example.com/hello',
        id: "22"    
    },
    {
        url: 'www.example.com/hello-how-are-you',
        id: "23"    
    },
    {
        url: 'www.example.com/i-like-cats',
        id: "24"    
    },
    {
        url: 'www.example.com/i-like-pie',
        id: "25"    
    }
]

使用Lodash,我怎样才能删除具有重复id键的对象?
有过滤器,地图和唯一的东西,但不太确定。

With Lodash, how could I remove objects with duplicate id keys? Something with filter, map and unique, but not quite sure.

我的真实数据集要大得多,键有更多,但概念应该是相同。

My real data set is much larger and has more keys, but the concept should be the same.

推荐答案

_。uniq 不再适用于当前版本因为lodash 4.0.0有这一重大变化。所以要使用

_.uniq no longer work for the current version as lodash 4.0.0 has this breaking change. So use either

_.uniqBy(data, function (e) {
  return e.id;
});

_.uniqBy(data, 'id');

文档: https ://lodash.com/docs#uniqBy

旧版本的lodash(< 4.0) .0)

For older versions of lodash( < 4.0.0 )

假设数据应该由 id 唯一,并且您的数据存储在<$ c $中c> data 变量,您可以使用 uniq()这样的函数:

Assuming that the data should be unique by id and your data is stored in data variable, you can use uniq() function like this:

_.uniq(data, function (e) {
  return e.id;
});

或者只是

_.uniq(data, 'id');

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

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