如何循环使用此JSON?

时间:2014-03-27 21:17:24

标签: javascript jquery json

我从PHP脚本返回了以下JSON

var data ={ 
            "first thing"  :["1","2"],
            "second thing" :["5","7"],
            "third thing"  :["8","2"]
           };

我知道我可以访问这样的项目:

console.log(data["first thing"]);

但是,我需要遍历它们并将它们应用到某个html中,并且对象名称将会改变,那么我如何才能让循环系统地通过它们并根据需要应用?基本上我首先需要遍历并应用名称,然后我将再次循环并应用值对。

 processResults:function(data){
         $('.thisclass').each(function(){
             $(this).html('put first json name here, so "first thing"')
             //then continue to loop through and apply next object name
         });
 }

然后在下一个循环中我需要做这样的事情:

 processResults:function(data){
         $('.nextclass').each(function(){
             $(this).html('put first of two values here, so "1"')
             //then continue to loop through and apply next object value
         });
 }

问题是我不知道怎么做而没有用括号表示法指定对象名称!

3 个答案:

答案 0 :(得分:3)

您可以尝试这样做(因为它标有jQuery):

$.each(yourObject, function(key, element){
    //key will be like "first thing" and so-
    //element will be an array.

    //it's true that yourObject[key] == element
    $.each(element, function(arrayIndex, arrayElement) {
        //process each arrayElement here
        //it's true that element[arrayIndex] == arrayElement
    })
})

答案 1 :(得分:1)

var data ={ 
    "first thing"  :["1","2"],
    "second thing" :["5","7"],
    "third thing"  :["8","2"]
};

$.each(data, function (key, arr) {
    console.log(key);
    var i = 0;
    for(i; i < arr.length; i++) {
        console.log(arr[i]);
    }
})

答案 2 :(得分:0)

您可以这样做:

var data ={
        "first thing"  :["1","2"],
        "second thing" :["5","7"],
        "third thing"  :["8","2"]
       };
//this will print all the key names
for (var key in data) {
  console.log(key);
}

//this will print the key values.
for (var key in data) {
  console.log(data[key]);
}

现在你只需要根据自己的需要进行调整。