2016-11-02 4 views
0

맘 객체 배열 가지고lodash uniqWith가

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

이것은 단지 기본적인 예이다, 데이터는 훨씬 더 복잡하므로 _.isEqual 작동하지 않을 것이다.

비교기로 무엇을합니까? 나는 그들이 동등한 경우에 id를 비교하고 싶다.

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

+1

오리의 대답은 uniqWith에 대한 올바른 하나입니다. 또한 [uniqBy] (https://lodash.com/docs/4.16.6#uniqBy)를 사용하여 해결할 수 있습니다 :'var result = _uniqBy (data, 'id)' –

+0

@GruffBunny - 답변에 추가했습니다. . –

답변

4

_.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>

+0

아 감사합니다. 나는 그것이 두 개의 매개 변수를 받아 들일지 모른다. – Jan

+0

당신은 환영합니다 :) –