밑줄에서 특정 키 값이있는 항목을 성공적으로 찾을 수 있습니다.
var tv = [{id:1},{id:2}]
var voteID = 2;
var data = _.find(tv, function(voteItem){ return voteItem.id == voteID; });
//data = { id: 2 }
하지만 객체가 발생한 배열 인덱스를 어떻게 찾습니까?
밑줄에서 특정 키 값이있는 항목을 성공적으로 찾을 수 있습니다.
var tv = [{id:1},{id:2}]
var voteID = 2;
var data = _.find(tv, function(voteItem){ return voteItem.id == voteID; });
//data = { id: 2 }
하지만 객체가 발생한 배열 인덱스를 어떻게 찾습니까?
findIndex
:var dataIndex = _.findIndex(tv, { id: voteID })
답변:
이 작업을 수행하는 기존 밑줄 방법이 있는지 모르겠지만 일반 자바 스크립트로 동일한 결과를 얻을 수 있습니다.
Array.prototype.getIndexBy = function (name, value) {
for (var i = 0; i < this.length; i++) {
if (this[i][name] == value) {
return i;
}
}
return -1;
}
그런 다음 다음을 수행 할 수 있습니다.
var data = tv[tv.getIndexBy("id", 2)]
return -1;
기본적으로 왜 안 됩니까?
findIndex
1.8에서 추가되었습니다.
index = _.findIndex(tv, function(voteItem) { return voteItem.id == voteID })
참조 : http://underscorejs.org/#findIndex
또는 다른 임시 목록을 만들어도 괜찮다면 다음과 같이 작동합니다.
index = _.indexOf(_.pluck(tv, 'id'), voteId);
index = _.findIndex(tv, {id: voteID})
경우 생성도 작동, 작동을 tv
컬렉션 이상 (개 단지 이상의 값 복잡했다 id
속성)
조건 자 함수가 더 유연해질 수 있도록 밑줄을 유지하려면 여기에 두 가지 아이디어가 있습니다.
for 술어 _.find
는 요소의 값과 색인을 모두 수신하므로 다음과 같이 부작용을 사용하여 색인을 검색 할 수 있습니다.
var idx;
_.find(tv, function(voteItem, voteIdx){
if(voteItem.id == voteID){ idx = voteIdx; return true;};
});
밑줄 소스를 살펴보면 다음과 같이 _.find
구현됩니다.
_.find = _.detect = function(obj, predicate, context) {
var result;
any(obj, function(value, index, list) {
if (predicate.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
이것을 findIndex
함수로 만들려면 줄 result = value;
을 result = index;
This is the same idea with the first method.로 바꾸면됩니다. 밑줄은 부작용도 구현한다는 점을 지적하기 위해 포함했습니다 _.find
.
대상 환경이 ES2015를 지원하는 경우 (또는 Babel과 같은 트랜스 파일 단계가있는 경우) 네이티브 Array.prototype.findIndex ()를 사용할 수 있습니다.
예를 들어
const array = [ {id:1}, {id:2} ]
const desiredId = 2;
const index = array.findIndex(obj => obj.id === desiredId);
간단하게 유지 :
// Find the index of the first element in array
// meeting specified condition.
//
var findIndex = function(arr, cond) {
var i, x;
for (i in arr) {
x = arr[i];
if (cond(x)) return parseInt(i);
}
};
var idIsTwo = function(x) { return x.id == 2 }
var tv = [ {id: 1}, {id: 2} ]
var i = findIndex(tv, idIsTwo) // 1
또는 싫어하지 않는 사람의 경우 CoffeeScript 변형 :
findIndex = (arr, cond) ->
for i, x of arr
return parseInt(i) if cond(x)
return parseInt(i) for i, x of array when cond(x)
비슷한 경우가 있지만 반대로 주어진 객체의 인덱스를 기반으로 사용되는 키를 찾는 것입니다. 발생한 인덱스를 얻기 위해 배열에 개체를 반환 하는 데 사용 하는 밑줄 에서 솔루션을 찾을 수 있습니다 Object.values
.
var tv = {id1:1,id2:2};
var voteIndex = 1;
console.log(_.findKey(tv, function(item) {
return _.indexOf(Object.values(tv), item) == voteIndex;
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>