2016-12-16 22 views
1

我需要在複雜的json /數組中搜索一個值,並且需要在對象中執行更新。我的JSON /陣列是:在複雜的json /數組中搜索位置以更新javascript(angularjs或純)

var myArray = [{ 
      "id": 5424, 
      "description": "xxxxxxxx", 
      "children": [{ 
       "id": 8756, 
       "description": "yyyyyyy", 
       "Children": [{ 
         "id": 8759, 
         "description": "zzzzzzz", 
         "Children": [{}] 
        }] 
      }] 
     }, 
     { 
      "id": 5675, 
      "description": "bbbbbbb", 
      "Children": [{}] 
     }]; 

我該怎麼做?我嘗試使用indexOf,find,map但沒有得到!

+0

什麼值見例如this jsfiddle你需要搜索/更新? – devqon

+0

你把jQuery標籤,你想要一個jQuery解決方案? – Malkev

+0

我使用的是angularjs,但jquery也可以是解決方案 –

回答

0

您可以創建一個遞歸函數(純JavaScript):

function updatePerson(id, propToUpdate, value) { 
    var person = findPerson(id, myArray); 
    if (person) { 
     person[propToUpdate] = value; 
    } 
} 

function findPerson(id, children) { 
    var found; 
    for (var i = 0; i < children.length; i++) { 
     var child = children[i]; 

     if (child.id == id) { 
      found = child; 
      break; 
     } else if (child.children && child.children.length) { 
      found = findPerson(id, child.children); 
      if (found) { 
       break; 
      } 
     } 
    } 

    return found; 
} 

在角