我尝试使用来自JSON文件的数据创建变量,尽管它仍然显示为未定义。检查显示选项对象,并显示以下错误:
此代码的目标是使用第一个JSON对象配置产品,然后使用第二个json对象提取有关产品选项的额外信息。
代码应该输出
的标题"cover-silk": ["150gsm-silk-cover"]
存储在第二个JSON对象
中变量childTitle应该=" 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);
}
};
&#13;
答案 0 :(得分:3)
我做了很多改变。整个结构不对。查看以下评论和工作片段:
<强>段强>
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: