2013-01-08 75 views
12

可能重複訪問對象:
I have a nested data structure/JSON, how can I access a specific value?在JSON陣列(JavaScript的)

我有在JSON數組返回嵌套對象的一項服務。我怎樣才能遍歷對象並打印所需的數據?

這是我的結果:

[ 
{ 
    "item1": { 
     "sourceUuid": "5599ffac-4b99-47c7-9370-a25e7e465429", 
     "targetUuid": "5599ffac-4b99-47c7-9370-a25e7effffff" 
    } 
}, 
{ 
    "item2": { 
     "sourceUuid": "bf63fe50-8b2b-488d-b565-009fcaebdb45", 
     "targetUuid": "-1" 
    } 
}, 
{ 
    "item3": { 
     "sourceUuid": "0005fd96-f654-4781-8602-09fedc0cdd35", 
     "targetUuid": "0005fd96-f654-4781-8602-09fedc0cdd35" 
    } 
} 
] 

這是我要打印每個項目(項目1,項目2,項目3,...)是什麼:

Item Name: item1 
Source: 5599ffac-4b99-47c7-9370-a25e7e465429 
Target: 5599ffac-4b99-47c7-9370-a25e7effffff 

到目前爲止,我嘗試:

for (var i = 0, length = data.length; i < length; i++) { 
for (obj in data[i]) { 
    console.log(obj); 

} 
} 

這僅返回「物品1」,「ITEM2」等,但我不知道如何訪問sourceUuid等從那裏

回答

31

您可以循環使用for loop陣列與for-in loops對象屬性。

for (var i=0; i<result.length; i++) 
    for (var name in result[i]) { 
     console.log("Item name: "+name); 
     console.log("Source: "+result[i][name].sourceUuid); 
     console.log("Target: "+result[i][name].targetUuid); 
    } 
+0

感謝您的好友:) – edward

5

使用循環

for(var i = 0; i < obj.length; ++i){ 
    //do something with obj[i] 
    for(var ind in obj[i]) { 
     console.log(ind); 
     for(var vals in obj[i][ind]){ 
      console.log(vals, obj[i][ind][vals]); 
     } 
    } 
} 

演示:http://jsfiddle.net/maniator/pngmL/

+0

我想用它在玉之後。或者angularjs。 – mcbjam