Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
164
rated 0 times [  168] [ 4]  / answers: 1 / hits: 124057  / 12 Years ago, tue, january 8, 2013, 12:00:00

Possible Duplicate:

I have a nested data structure / JSON, how can I access a specific value?






I have a service that returns nested Objects in a JSON Array. How can I loop through the objects and print the desired data?



This is my result:



[
{
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
}
}
]


This is what I want to print for each item (item1, item2, item3, ...):



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


So far I tried:



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

}
}


This only returns item1, item2 etc. But I don't know how access sourceUuid etc. from there


More From » arrays

 Answers
36

You can loop the array with a for loop and the object properties with 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);
}

[#81007] Monday, January 7, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
calicinthias

Total Points: 447
Total Questions: 101
Total Answers: 118

Location: Botswana
Member since Sat, Dec 31, 2022
1 Year ago
calicinthias questions
Sun, Jan 2, 22, 00:00, 2 Years ago
Wed, Jan 13, 21, 00:00, 3 Years ago
Mon, Aug 10, 20, 00:00, 4 Years ago
;