0

I have this problem: I have a JSON object and I want to iterate on it in a javascript function, but it is composed of other JSON objects. It is, for example:

[ 
    {"id"="1", "result"=[{"name"="Sam","age"="12"},{"sport"="soccer"}]},
    {"id"="2", "result"=[{"name"="Paul","age"="43"},{"sport"="basketball"}]}
]

And I would iterate on it to work with values, in this way:
1) on first iteration: I want to work with: "Sam", "12", "soccer"
2) on second iteration: I want to work with: "Paul", "43", "basketball"
and so on.

Can you help me for this problem?

Code Lღver
  • 15,573
  • 16
  • 56
  • 75
  • 3
    JSON is *not an object*, it is a **string**, i.e. serialized representation of JavaScript object. – VisioN Apr 24 '13 at 10:17
  • possible duplicate of [I have a nested data structure / JSON, how can I access a specific value?](http://stackoverflow.com/questions/11922383/i-have-a-nested-data-structure-json-how-can-i-access-a-specific-value) – Felix Kling Apr 24 '13 at 10:20
  • FWIW, what you posted is neither JSON nor valid JavaScript. – Felix Kling Apr 24 '13 at 10:20
  • why is result an array of dissimilar objects? It might make your code more readable if it was an object with named properties, or if you removed the result property all together. – Tom Elmore Apr 24 '13 at 10:23

1 Answers1

1

First you must fix your object literal. You must use : not = for the key-value pairs.

After that you can iterate in the following way:

var obj = [ {"id":"1", "result":[{"name":"Sam","age":"12"},{"sport":"soccer"}]},
{"id":"2", "result":[{"name":"Paul","age":"43"},{"sport":"basketball"}]}];

for (var i = 0; i < obj.length; i += 1) {
    console.log("Name", obj[i].result[0].name);
    console.log("Age", obj[i].result[0].age);
    console.log("Sport", obj[i].result[1].sport);
}

If you want to do the whole traversal with loops you can use:

var obj = [ {"id":"1", "result":[{"name":"Sam","age":"12"},{"sport":"soccer"}]},
{"id":"2", "result":[{"name":"Paul","age":"43"},{"sport":"basketball"}]}];

for (var i = 0; i < obj.length; i += 1) {
    for (var j = 0; j < obj[i].result.length; j += 1) {
       var current = obj[i].result[j];
       for (var prop in current) {
          console.log(prop, current[prop]);
       }
    }
}
Minko Gechev
  • 25,304
  • 9
  • 61
  • 68
  • But, if I have too many key-value pairs in the field result, and too many objects in the original object, so it's impossible to write a line in the code for each of them, how can I do if I want all the values? –  Apr 24 '13 at 10:37