Reputation: 615
I'm trying to make a variable using data from a JSON file, though it keeps showing as undefined. inspection shows the options object with the following error:
The goal from this code is to configure a product using the first JSON object and then pull in extra information about the product options using the second json object.
The code should output the title of
"cover-silk": ["150gsm-silk-cover"]
which is stored in the second JSON object
The variable childTitle should = "150gsm"
productData = {
"product": [{
"name": "booklet",
"section": [{
"coverStock": {
"cover-silk": ["150gsm-silk-cover"]
}
}]
}]
}, {
"section2": {
"coverStock": [{
"title": "Cover Stock",
"options": [{
"cover-silk": {
"title": "Silk",
"childOptions": {
"150gsm-silk-cover": {
"title": "150gsm"
}
}
}
}]
}]
}
};
var key = productData.product[0].section[0];
var keys = [];
for (var k in key) keys.push(k);
var len = keys.length;
for (var i = 0; i < len; i++) {
var option = productData.product[0].section[0][keys[i]];
var secObj = (option);
var secObjArray = [];
for (var k2 in secObj) secObjArray.push(k2);
var len2 = secObjArray.length;
for (var j = 0; j < len2; j++) {
var childTitle = productData.section2[keys[i]][0].options[0][secObjArray][j].title;
console.log(childTitle);
}
};
Upvotes: 1
Views: 181
Reputation: 167162
I have made a lot of changes. The whole structure wasn't right. Check out the comments below and working snippet too:
Snippet
var productData = {
"product": [{
"name": "booklet",
"section": [{
"coverStock": {
"cover-silk": ["200gsm-silk-cover", "250gsm-silk-cover"],
"cover-gloss": ["300gsm-gloss-cover", "250gsm-gloss-cover"]
}
}],
"section2": {
"coverStock": [{
"title": "Cover Stock",
"options": [{
"cover-silk": {
"title": "Silk",
"childOptions": {
"150gsm-silk-cover": {
"title": "150gsm"
}
}
}
}]
}]
}
}]
};
var key = productData.product[0].section[0];
var keys = [];
for (var k in key)
keys.push(k);
var len = keys.length;
for (var i = 0; i < len; i++) {
var option = productData.product[0].section[0][keys[i]];
var secObj = option;
var secObjArray = [];
for (var k2 in secObj)
secObjArray.push(k2);
var len2 = secObjArray.length;
for (j = 0; j < len2; j++) {
var childTitle = productData.product[0].section[0][keys[i]][secObjArray[j]][0];
console.log(childTitle);
}
}
Diff:
If you are interested, this is the Diff:
Upvotes: 3