DEV Community

打coding的奥特曼
打coding的奥特曼

Posted on

补充一个对象数组去重

const _ = require('lodash') ;
const arr = [{a:1},{b:1},{c:1},{c:1},{e:1},{a:1}];
const res = _.uniqWith(arr,_.isEqual);
console.log(res);//[ { a: 1 }, { b: 1 }, { c: 1 }, { e: 1 } ]
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
kongfuboy123 profile image
打coding的奥特曼

如果没有第三方库靠手写过滤的话,我想可能得先看看对象的的格式,看看是否可以取巧,如果是[{id: '1',name: 'a',{id: '2',name: 'b']这种,就可以直接比较id取巧,如果是我例子那样,那就分别比较键名跟键值,但如果对象树比较深的话,可能就得写递归逐key比较了,不知道我的想法是否恰当。By the way ,如果你有什么好的方法的话,希望不吝赐教,不胜感激。

Collapse
 
kongfuboy123 profile image
打coding的奥特曼

_.isEqual 是lodash的深比较方法,可以用来比较对象,但无视对象内部排序不同