我有这个Json字符串,A和B可以是从我的服务器发送的自定义名称。
Json String
{
"basketContent": {
"A": {
"Apples": "22",
"Avocado": "43"
},
"B": {
"Banana": "62",
"Blueberry": "1"
}
},
"basketOwner": "Anne"
}
的Javascript
var jsonData= JSON.parse(jsonString);
for (var i in jsonData.basketContent) {
var c= jsonData.basketContent[i];
console.log(c.[0][0]);
}
如何在不需要命名的情况下迭代basketContents?有解决方法吗?
答案 0 :(得分:1)
您可以递归遍历对象:
var obj = {
"basketContent": {
"A": {
"Apples": "22",
"Avocado": "43"
},
"B": {
"Banana": "62",
"Blueberry": "1"
}
},
"basketOwner": "Anne"
};
function print(obj,key){
if(typeof obj == "object"){
for(var key in obj){
print(obj[key],key);
}
}else{
console.log(key);
console.log(obj);
}
}
print(obj);