Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
183
rated 0 times [  184] [ 1]  / answers: 1 / hits: 103765  / 11 Years ago, thu, march 7, 2013, 12:00:00

I have to iterate through json array object.



It has following structure.



var myJSONObject = {
abc: {
prod_1: [
{prod_ver : prod 1 ver 1},
{prod_ver : prod 1 ver 2},
],
prod_2: [
{prod_ver : prod 2 ver 1},
{prod_ver : prod 2 ver 2},
],
prod_3: [
{prod_ver : prod 3 ver 1},
{prod_ver : prod 3 ver 2},
]
}
};


Basically what I am doing is prod_1 is name of a product and the list of versions that prod_1 has are populated inside it.



So now what i want is the name of the product as well as what versions it has.



The problem is there can be many products and many versions under that product.
So i need a proper looping structure in javascript that can be generic to handle it.



It would be best if the loop stores product name in one var and it's version in another var as there are some checking i need to on product name.



If the json structure is wrong or a better json structure can be written the please suggest a right/better structure.



Please HELP



Thanks in advance.


More From » json

 Answers
16

Since myJSONObject.abc contains a list of products it would make more sense to define the property abc as an array. Like this:



var myJSONObject = 
{
abc:
[
[
{prod_ver : prod 1 ver 1},
{prod_ver : prod 1 ver 2},
],
[
{prod_ver : prod 2 ver 1},
{prod_ver : prod 2 ver 2},
],
[
{prod_ver : prod 3 ver 1},
{prod_ver : prod 3 ver 2},
]
]
};


Then you can iterate over the products and their versions using normal loops:



for(var i = 0; i < myJSONObject.abc.length; i++)
{
var product = myJSONObject.abc[i];
for(var j = 0; j < product.length; j++)
{
var version = product[j];
}
}


You could take it slightly further and alter your JSON object's structure a bit to make it more easily understandable.



var catalog = 
{
products: [
{
name: prod 1,
versions: [
ver 1,
ver 2
]
},
{
name: prod 2,
versions: [
ver 1,
ver 2
]
}
]
};

for(var i = 0; i < catalog.products.length; i++)
{
var product = catalog.products[i];
var productName = product.name;
for(var j = 0; j < product.versions.length; j++)
{
var version = product.versions[j];
}
}

[#79770] Wednesday, March 6, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
richardaydenc

Total Points: 148
Total Questions: 125
Total Answers: 98

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
;