2015-01-30 5 views
0

와 배열에서 객체의 위치를 ​​취득하는 것은 이제 다음과 같은 I 배열을 가정 해 봅시다 :JS/jQuery를

[ 
    { 
     "name": "list", 
     "text": "SomeText1" 
    }, 
    { 
     "name": "complex", 
     "text": "SomeText2", 
     "config": { 
      "name": "configItem", 
      "text": "SomeText3", 
      "anotherObject": { 
       "name": "anotherObject1", 
       "text": "SomeText4" 
      } 
     } 
    } 
] 

을 내가 특정 키 (http://techslides.com/how-to-parse-and-search-json-in-javascript) 모든 객체를 얻기 위해이 멋진 코드를 사용하고 있습니다. 필자의 예에서는 getObjects(data,'text','')으로, 텍스트를 키로 사용하여 모든 노드를 Object로 반환합니다.

내 유일한 문제는 전체 배열에서 반환 된 Object의 위치를 ​​알아야한다는 것입니다.

가져올 방법이 있습니까? 아니면 적어도 배열과 결합 된 객체의 깊이?

getObjects(r,'text','')[0] (NAME = 목록) -> 깊이 1

getObjects(r,'text','')[1] (NAME = 착체) -> 깊이 1

getObjects(r,'text','')[2] (NAME = configItem) -> 깊이 2

+0

가능한 [개체의 깊이를 확인하는 방법?] (http://stackoverflow.com/questions/13523951/how-to-check-the-depth-of-an-object) – Alex

+0

글쎄, 나는 객체의 가장 깊은 레벨을 필요로하지 않습니다. - 배열에서 주어진 객체의 정확한 깊이가 필요합니다. 따라서,이 링크는 도움이되지 않습니다. – user1021605

+0

가능한 [Javascript 개체로 구성된 Javascript 배열의 indexOf 가져 오기] (http://stackoverflow.com/questions/7908810/getting-indexof-javascript-array-made-up-of-javascript-objects) – Michelangelo

답변

2

당신은이 라인을 따라 뭔가해야합니다

function getObjectsDepth(obj, key, val, depth) { 
    var objects = []; 
    for (var i in obj) { 
     if (!obj.hasOwnProperty(i)) continue; 
     if (typeof obj[i] == 'object') { 
      objects = objects.concat(getObjectsDepth(obj[i], key, val,++depth));  
     } else 
     //if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not) 
     if (i == key && obj[i] == val || i == key && val == '') { // 
      objects.push(depth); 
     } else if (obj[i] == val && key == ''){ 
      //only add if the object is not already in the array 
      if (objects.lastIndexOf(obj) == -1){ 
       objects.push(depth); 
      } 
     } 
    } 
    return objects; 
} 

이 객체의 깊이를 반환합니다,하지만 당신이 방법을 객체 자체가 아니라, 그냥 기반으로, 0 또는 1로 마지막 PARAM을 통과 카운트. 개체와 깊이가 동시에 필요하면 obj.push({'obj':obj,'depth':depth})이 필요합니다.

+0

감사합니다! 다른 문제가 있습니다. 내 배열에 객체가 있지만 getObjects (r, 'config', '')를 호출하면 반환 값 ist가 null입니다. – user1021605

+0

'config'가 객체이기 때문에 그냥 건너 뜁니다. 'if (typeof obj [i] == 'object') {'다음에'objects.push (obj);를 추가하여 그것도 얻으십시오. –

+0

이것은 내가 key = text를 quering 할 때 원하지 않는 많은 returnvalues를 줄 것입니다. 제가 이것을 디버깅 할 필요가 있다고 생각합니다 - 미리 감사드립니다. – user1021605

1

변경있는 getObjects 함수 이 사람 :

function getObjects(obj, key, val, depth) { 
    var objects = []; 
    depth = typeof depth !== 'undefined' ? depth : 0; 
    for (var i in obj) { 
     if (!obj.hasOwnProperty(i)) continue; 
     if (typeof obj[i] == 'object') { 
      depth ++; 
      objects = objects.concat(getObjects(obj[i], key, val, depth));  
     } else 
     //if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not) 
     if (i == key && obj[i] == val || i == key && val == '') { // 
      objects.push({"obj":obj,"depth": depth}); 
     } else if (obj[i] == val && key == ''){ 
      //only add if the object is not already in the array 
      if (objects.lastIndexOf(obj) == -1){ 
       objects.push({"obj":obj,"depth": depth}); 
      } 
     } 
    } 
    return objects; 
} 

이제 깊이와 개체를 얻습니다.