2010-12-12 3 views
1

숫자 값을 기준으로 자바 스크립트 배열을 정렬하는 방법에 대한 예제가 많이 있습니다. 그러나 prop1 속성을 가진 myArray에서 모든 요소를 ​​가져 오는 것이 적절한 방법은 무엇입니까? 값이 value1일까요? 하는 임의의 속성을 기준으로 정렬하는 기능을 비교자바 스크립트 : 2 차원 배열 필터링

var myArray = [ 
{ 
    "id":"2", 
    "name":"My name", 
    "properties":{"prop1":"value1"} 
}]; 

감사

답변

2
당신은 그냥 점으로 액세스 할 수 있습니다

또는 대괄호 표기법을 사용하고 일치하는 멤버를 n EW/예를 들어, 배열을 필터링 : 당신은 그럼 그냥 newArray.push(myArray[i].properties)newArray.push(myArray[i])을 변경 {"prop1":"value1"} 객체가 아닌 부모를 얻으려고 노력하는 경우

var newArray = []; 
for(var i=0, l = myArray.length; i<l; i++) { 
    if(myArray[i].properties.prop1 == "value1") newArray.push(myArray[i]); 
} 

귀하의 질문은,하지만 조금 모호합니다.

+0

정말 깨끗한 해결책입니다. 고마워요! – Industrial

+0

안녕하세요 닉 - 제발 여기 좀 봐; http://stackoverflow.com/questions/4433004/jquery-js-sorting-array-based-upon-another-array – Industrial

1

제공 : 여기

내 배열의

function compareMyObjects(a, b) { 
    var valA = a.properties.prop1.value1; 
    var valB = b.properties.prop1.value1; 

    if(valA > valB) return 1; 
    if(valA < valB) return -1; 
    return 0; 
} 

myArray.sort(compareMyObjects); 

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

+0

이 * 종류 * 배열은 필터링하지 않습니다. 또한'prop1'은 문자열입니다. 그래서 여러분은 너무 멀리 정렬에 왔습니다. :) –

0

배열의 각 요소를 살펴보십시오. 각 요소에 대해 각 속성을 확인하여 원하는 속성과 일치하는지 확인합니다.

function filterArray(array, property, value) { 
    var newArray = []; 
    for (var i = 0; i < array.length; i++) { 
     for (var j in array[i].properties) { 
      if (j === property && array[i].properties.hasOwnProperty(j)) { 
       if (array[i].properties[j] == value) { 
        newArray.push(array[i]); 
       } 
      } 
     } 
    } 
} 
+0

이것은 어디에서나 값을 확인하지 않고 새로운 객체를 새로운 배열로 여러 번 푸시합니다. 하나 이상의 자식 속성이있는 경우에도 마찬가지입니다. –

+0

해결되었습니다. 게시 직후 실수를 느꼈다. – mdarwi

+0

왜 루프를 통해 속성에 직접 액세스 할 수 있습니까? :) –

0
var newarray=myarray.filter(function(itm){ 
    return itm.properties.prop1==='value1'; 
}); 

필터, 배열 방법 같이 IndexOf와지도처럼,이 버전은 모질라 개발자에서입니다 - 그것을를하지 않아도 브라우저에서 제공하는 가치가있을 수 있습니다 사이트 -

if(!Array.prototype.filter){ 
    Array.prototype.filter= function(fun, scope){ 
     var L= this.length, A= [], i= 0, val; 
     if(typeof fun== 'function'){ 
      while(i< L){ 
       if(i in this){ 
        val= this[i]; 
        if(fun.call(scope, val, i, this)){ 
         A[A.length]= val; 
        } 
       } 
       ++i; 
      } 
     } 
     return A; 
    } 
}