我有一系列对象,如:
[{id: '123', name: 'John', someKey:'1234'}, {id: '123', name: 'John', someKey:'12345'}]
这只是一个基本的例子,数据要复杂得多,_.isEqual
无效。
我该如何处理比较器?如果它们相等,我想比较id
。
_.uniqWith(myArray, function(something) {return something})
答案 0 :(得分:6)
比较_.uniqWith()
比较器函数中的ID或使用_.uniqBy()
:
var myArray = [{
id: '123',
name: 'John',
someKey: '1234'
}, {
id: '123',
name: 'John',
someKey: '12345'
}]
var result = _.uniqWith(myArray, function(arrVal, othVal) {
return arrVal.id === othVal.id;
});
console.log(result);
/** using uniqBy **/
var result = _.uniqBy(myArray, 'id');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>