lodash uniqWith与一组对象

时间:2016-11-02 13:57:17

标签: lodash

我有一系列对象,如:

[{id: '123', name: 'John', someKey:'1234'}, {id: '123', name: 'John', someKey:'12345'}]

这只是一个基本的例子,数据要复杂得多,_.isEqual无效。

我该如何处理比较器?如果它们相等,我想比较id

_.uniqWith(myArray, function(something) {return something})

1 个答案:

答案 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>