2010-07-13 7 views
11

개체 배열이 있습니다. 각 개체에는 ID 특성이 있습니다. 나는 특정 ID를 가진 객체의 배열에서 색인을 찾고 싶다. jQuery에서 우아하고 간단한 방법이 있습니까?jQuery : 배열의 요소 색인 어디에서 술어

+0

정확히 내가 무엇을 찾고 있는지. 참으로 나쁜 해결책이 없다 ... – epeleg

답변

4

이 경우에는 for 루프를 jQuery 대신 javascript에 사용해야합니다. 방법 3을 참조하십시오 http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/

업데이트 : jQuery는 자바 스크립트로 작성되었으며 자바 스크립트로 작성된 다른 코드보다 빠를 수 없습니다. DOM을 사용하여 작업하는 경우 jQuery는 매우 유용하지만 단순한 자바 스크립트 배열이나 객체로 작업하는 경우에는 도움이되지 않습니다.

for (var i=0, l = ar.length; i<l; i++) { 
    if (ar[i].ID === specificID) { 
     // i is the index. You can use it here directly or make a break 
     // and use i after the loop (variables in javascript declared 
     // in a block can be used anywhere in the same function) 
     break; 
    } 
} 
if (i<l) { 
    // i is the index 
} 

중요 몇 가지 간단한 자바 스크립트 규칙을 유지해야 : 항상 지역 변수 (변수 선언하기 전에 var을 잊지 마세요) 및 캐시를 선언

당신이 찾고있는 코드는 다음과 같은 수 있습니다 위의 ar.length과 같은 로컬 변수에서 두 번 이상 사용하는 속성이나 인덱스 당신이 백필 수

체크 아웃 findIndexfindIndex 이후

items.findIndex(function(item) { item.property == valueToSearch; }); 

ECMAScript를 6에서 아직 대부분의 브라우저에서 사용할 수 없습니다 :

3

정말 우아한 아니지만, 귀여운 트릭 :

var index = parseInt(
    $.map(array, function(i, o) { return o.id === target ? i : ''; }).join('') 
); 

jQuery를 그런 기능적인 구조의 여지가없는; 도서관의 철학은 실제로 DOM 논쟁의 일에 집중되어 있습니다. 아무도 핵심 기능에 유용 할 이유를 생각할 수 없기 때문에 그들은 .reduce() 기능을 추가하지 않습니다.

Underscore.js 라이브러리에는 이러한 기능이 많이 있으며 jQuery로 "훌륭하게"재생됩니다.

+0

배열의 모든 요소를 ​​다루기 때문에 멋지지만 비효율적이다. ... 만약 당신이 그것들을 지나치면, 리버스 해쉬를 만들 수도있다. 그래서 많은 사람들이 Q에 대답 할 수있다. "specificID"입니다. – epeleg

+0

@epeleg 그래, 분명히. – Pointy

5
 
See [`Array.filter`][1] to filter an array with a callback function. Each object in the array will be passed to the callback function one by one. The callback function must return `true` if the value is to be included, or false if not. 

    var matchingIDs = objects.filter(function(o) { 
     return o.ID == searchTerm; 
    }); 

All objects having the ID as searchTerm will be returned as an array to matchingIDs. Get the matching element from the first index (assuming ID is unique and there's only gonna be one) 

    matchingIDs[0]; 

    [1]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter 

업데이트 (http://wiki.forum.nokia.com/index.php/JavaScript_Performance_Best_Practices 예를 들어, 참조) 그것을 사용하는이 implementation :

if (!Array.prototype.findIndex) { 
    Array.prototype.findIndex = function(predicate) { 
    if (this == null) { 
     throw new TypeError('Array.prototype.findIndex called on null or undefined'); 
    } 
    if (typeof predicate !== 'function') { 
     throw new TypeError('predicate must be a function'); 
    } 
    var list = Object(this); 
    var length = list.length >>> 0; 
    var thisArg = arguments[1]; 
    var value; 

    for (var i = 0; i < length; i++) { 
     value = list[i]; 
     if (predicate.call(thisArg, value, i, list)) { 
     return i; 
     } 
    } 
    return -1; 
    }; 
} 
+2

OP는 요소 자체의 색인이 아닌 요소의 색인을 얻는 방법을 질문했습니다. – epeleg

+0

@epeleg - 질문을 제대로 읽지 못했습니다. Oleg가 제안한대로 각 개체를 반복하고 일치하는 항목이 발견되면 위반하는 것이 좋습니다. – Anurag

0

jOrder를 사용하십시오. http://github.com/danstocker/jorder

배열을 jOrder 테이블에 넣고 'ID'필드에 색인을 추가하십시오. 당신은 전체 행을 원한다면,

var arrayidx = table.index('id').lookup([{ ID: MyID }]); 

:

var table = jOrder(data) 
    .index('id', ['ID']); 

그런 다음에 의해 요소의 배열 인덱스를 얻을 수

var filtered = table.where([{ ID: MyID }]); 

짜잔합니다.

1

기본 제공되는 방법이 없습니다. [].indexOf() 방법은 조건을 고려하지 않습니다, 그래서 당신은 뭔가 정의해야합니다

function indexOf(array, predicate) 
{ 
    for (var i = 0, n = array.length; i != n; ++i) { 
     if (predicate(array[i])) { 
      return i; 
     } 
    } 
    return -1; 
} 

var index = indexOf(arr, function(item) { 
    return item.ID == 'foo'; 
}); 

함수는 -1을 반환 술어가 결코 truthy 값을 얻을 수없는 경우입니다.