Good day! There is a following JSON array:
{
"Boxes": [
{
"Name": "Hat Box",
"Flowers": "Roses",
"Types": {
"MINI": {
"SIZE": "15x15x15cm",
"Price": "1000"
},
"M": {
"Size": "20x20x21cm",
"Price": "1300"
},
"L": {
"Size": "22x22x23cm",
"Price": "1700"
}
}
},
{
"Name": "Box in the shape of a heart",
"Flowers": "White Roses",
"Types": {
"MINI": {
"SIZE": "16x13cm",
"Price": "1200"
},
"M": {
"Size": "19x15cm",
"Price": "1500"
},
"L": {
"Size": "22x17cm",
"Price": "1700"
}
}
}
}]
How to get, for example, all data from the “Types” element?
Those. I got all from Boxes:
$. GetJSON ('JS / Data.json', Function (DATA) {
For (var i = 0; i & lt; data.boxes.length; I ++) {
console.log ('Title:' + Data.Boxes [i] .name + '\ n');
}
});
But when trying to embed another FOR cycle, everything is covered with a copper pelvis.
UPD:
for (var key in data.boxes [i] .types {
Console.log ('Available types:' + Key);
}
After this code, accessible types appeared, i.e. “MINI”, “M” and “L” … But really you need to go through the entire multidimensional object?
Answer 1, Authority 100%
In the first place, this JSON is synthesically incorrect (the closing brackets are confused in the last line), in the second logical (subordinate Types objects are objects with the properties of “mini”, “M” and “L”, and not arrays with auto-index). However, arrays in JSON are also objects, properties in which are set automatically (“0”, “1”, “2”, …).
Based on your JSON logic should look:
{
"Boxes": [
{
"Name": "Hat Box",
"Flowers": "Roses",
"Types": [
"MINI": {
"SIZE": "15x15x15cm",
"Price": "1000"
},
"M": {
"Size": "20x20x21cm",
"Price": "1300"
},
"L": {
"Size": "22x22x23cm",
"Price": "1700"
}
]
},
{
"Name": "Box in the shape of a heart",
"Flowers": "White Roses",
"Types": [
"MINI": {
"SIZE": "16x13cm",
"Price": "1200"
},
"M": {
"Size": "19x15cm",
"Price": "1500"
},
"L": {
"Size": "22x17cm",
"Price": "1700"
}
]
}
]}
Then the first way to organize a cycle
will also work
for (var key1 = 0; i & lt; data.boxes.length; key1 ++) {
For (var key2 = 0; i & lt; data.boxes [key1] .types.length; Key2 ++) {
var something = data.Boxes [key1] .types [Key2];
...
But the second way is more versatile and more correct for JSON:
for (var key1 in data.boxes) {
For (var key2 in data.boxes [Key1] .types) {
var something = data.Boxes [key1] .types [Key2];
...
It will work with yours and with my JSON variants (provided that the closing brackets are properly placed).