Paddy Paddy - 3 months ago 9
Javascript Question

JSON/Javascript object definition

Trying to identify the type of array, I have an multidimensional JSON array that i pull from a website, but its not using keypairs i am farmiliar with. The structure is as follows. I have only included 1 array item to show what it's doing.

"o": {
"ah": ["id1", "12", "id2", "32", "id4", "4", "id5, "6"]
},


My searches on both JavaScript and JSON objects and strings always use a semi-colon : to define the key and the value.

In the end I just want to loop through the multiple items and print them out.

To provide more clarification about the array structure:

{
"outer": {
"item1":[ {
"c": {
"k": 26862, "n": "theName"
},
"o": {
"ah": ["id1", "0", "id2", "0", "id3", "0.98", "id4", "0.94", "id5", "5", "id6", "-0/0.5"],
"ou": ["id7", "3.5", "id8", "3.5", "id9", "1.53", "id10", "0.55", "id11", "3.4", "id12"],
"1x2": ["id13", "1.20", "id14", "25.00", "id15", "4.80"]
},
"egn":""
}
]
},
{
"item1":[ {
"c": {
"k": 26862, "n": "theName"
},
"o": {
"ah": ["bd1", "0", "bd2", "0", "bd3", "0.98", "bd4", "0.94", "bd5", "0.5", "bd6", "-0.5"],
"ou": ["bd7", "3.5", "bd8", "3.5", "bd9", "1.53", "bd10", "0.55", "bd11", "3.4", "bd12"],
"1x2": ["bd13", "1.20", "bd14", "25.00", "bd15", "4.80"]
},
"egn":""
}
]
}
}


If I wanted to bind an ID to a specific field e.g. and it display the value of ID 1 in the array structure how would I do it without a keypair value, also if the array ID is not standardized so you can't loop through like
var = "id"+ i
foreach element?

Answer

o is an object, ah is an array which is a property of o object. You use JSON.parse() to convert JSON string to javascript object, then iterate over o.ah using Array.prototype.forEach()

// or however you obtain the JSON string
var obj = JSON.parse(jsonStr); 
obj.o.ah.forEach(function(value) {
  console.log(value);
});