lodash를 사용하면 다음을 사용하여 기본 데이터 유형의 멤버십을 확인할 수 있습니다 includes.
_.includes([1, 2, 3], 2)
> true
그러나 다음은 작동하지 않습니다.
_.includes([{"a": 1}, {"b": 2}], {"b": 2})
> false
컬렉션을 검색하는 다음 방법이 제대로 작동하는 것처럼 보이기 때문에 혼란 스럽습니다.
_.where([{"a": 1}, {"b": 2}], {"b": 2})
> {"b": 2}
_.find([{"a": 1}, {"b": 2}], {"b": 2})
> {"b": 2}
내가 뭘 잘못하고 있죠? 컬렉션에서 개체의 멤버 자격을 어떻게 확인 includes합니까?
편집 : 질문은 원래 lodash 버전 2.4.1 용이며 lodash 4.0.0 용으로 업데이트되었습니다.
답변
includes(이전 contains과 include) 방법 (하여,보다 정확하게 또는 참조하여 오브젝트를 비교 ===). {"b": 2}예제에서 의 두 객체 리터럴 은 서로 다른 인스턴스 를 나타내 므로 같지 않습니다. 주의:
({"b": 2} === {"b": 2})
> false
그러나 다음과 같은 인스턴스가 하나만 있기 때문에 작동합니다 {"b": 2}.
var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true
반면에 where(v4에서 더 이상 사용되지 않음) 및 find메소드는 속성을 기준으로 객체를 비교하므로 참조 평등이 필요하지 않습니다. 에 대한 대안으로 includes시도 할 수도 있습니다 some( any).
_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true
답변
에 의해 해답을 보완 p.s.w.g, 여기에 사용이 달성의 다른 세 가지 방법 lodash 4.17.5, 사용하지 않고는 _.includes() :
객체 entry가 객체 배열에 아직 추가되지 않은 numbers경우에만 객체를 추가한다고 가정하십시오 entry.
let numbers = [
{ to: 1, from: 2 },
{ to: 3, from: 4 },
{ to: 5, from: 6 },
{ to: 7, from: 8 },
{ to: 1, from: 2 } // intentionally added duplicate
];
let entry = { to: 1, from: 2 };
/*
* 1. This will return the *index of the first* element that matches:
*/
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) });
// output: 0
/*
* 2. This will return the entry that matches. Even if the entry exists
* multiple time, it is only returned once.
*/
_.find(numbers, (o) => { return _.isMatch(o, entry) });
// output: {to: 1, from: 2}
/*
* 3. This will return an array of objects containing all the matches.
* If an entry exists multiple times, if is returned multiple times.
*/
_.filter(numbers, _.matches(entry));
// output: [{to: 1, from: 2}, {to: 1, from: 2}]
를 반환 Boolean하려면 첫 번째 경우 반환되는 인덱스를 확인할 수 있습니다.
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
// output: true
