0

我有这个 Json 字符串,A 和 B 可以是从我的服务器发送的自定义名称。

json字符串

{
    "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]);
   } 

如何在无需命名的情况下遍历购物篮内容?有解决方法吗?

4

1 回答 1

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);

工作示例 http://jsfiddle.net/eEQLW/1/

于 2013-06-04T08:55:12.177 回答