合并没有重复的角度2中的对象数组 [英] Merge Object arrays without duplicates in angular 2

查看:39
本文介绍了合并没有重复的角度2中的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular2/Typescript(ES6)中,合并没有重复项的两个数组的最快,最简单的方法是什么.

What is quickest and easiest way to merge two arrays without duplicates in Angular2/Typescript (ES6).

p.s.数组包含嵌套对象.

p.s. Arrays contain nested objects.

我知道那里已经有很多答案了.这就是为什么我很困惑.我在中尝试了答案,但我无法正常工作.

I know there are lot of answers already there. That's why I'm confused. I tried answers on this, but I couldn't get it working.

谢谢.

推荐答案

这与angular2/typescript无关,我的答案适用于ES6.

That's not related to angular2/typescript, my answer works with ES6.

使用lodash中的 uniq 函数( https://lodash.com/docs/4.17.4#uniq )来处理来自源数组的项目,如下所示:

Use uniq function from lodash (https://lodash.com/docs/4.17.4#uniq) on items from your sources array like this:

const arrA = [1, 2, 3, 4];
const arrB = [3, 4, 5, 6];
const arr = _.uniq([...arrA, ...arrB])
// [1, 2, 3, 4, 5, 6]

对于嵌套对象,请使用 uniqBy ( https://lodash.com/docs/4.17.4#uniqBy )或 uniqWith .

And for nested object, use uniqBy (https://lodash.com/docs/4.17.4#uniqBy) or uniqWith.

const arrA = [{id: 1, n: 'e'}, {id: 2, n: 'z'}];
const arrB = [{id: 2, n: 'z'}, {id: 3, n: 'c'}];
const arr = _.uniqBy([...arrA, ...arrB], 'id')
// [{id: 1, n: 'e'}, {id: 2, n: 'z'}, {id: 3, n: 'c'}]

但是您需要一个唯一的标识符(此处为 id )来知道何时重复.

But you need a unique identifier (id here) to know when duplicates.

,如果您没有唯一的标识符,并且想使用整个对象进行重复数据删除,则可以这样操作:

In case, you don't have a unique identifier and want to use whole objects to deduplicate, you can do it like this:

const arrA = [{a: 'a'}, {b: 'b'}];
const arrB = [{b: 'b'}, {c: 'c'}];
const arr = _.uniqBy([...arrA, ...arrB], JSON.stringify)
// [{a: 'a'}, {b: 'b'}, {c: 'c'}]

它将对所有对象进行字符串化处理,以检查是否具有相同的字符串值,因此请记住,在庞大的对象/数组上这样做可能会造成很大的代价.最好使用唯一的标识符.

It will stringify all your object to check if same string values, so remember it could be costly on huge objects/array. That's a better practise to have a unique identifier.

这篇关于合并没有重复的角度2中的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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