如何使用javascript获取对象索引值的JSON响应

时间:2014-12-09 06:50:53

标签: javascript jquery

我的JSON文字是

[{
        "album_name" : "marriage",
        "album_image" : "images/abc.jpg"
    }, {
        "album_name" : "holiday",
        "album_image" : "images/holi.jpg"
    }
]

因为我需要获得每个对象的索引值。我使用for循环获取上面的值并动态附加。我的要求是当我点击每个项目时,我需要在onclick函数中传递该对象的索引值。

2 个答案:

答案 0 :(得分:1)

关注json对象

 var json = [{"album_name":"marriage","album_image":"images/abc.jpg"},
             {"album_name":"holiday","album_image":"images/holi.jpg"}];

如果你想获得任何索引值,那么你可以这样做

console.log(json[0].album_name); // means 0 index album_name key value

使用forEach函数迭代JSON对象,

var json = [{"album_name":"marriage","album_image":"images/abc.jpg"},
            {"album_name":"holiday","album_image":"images/holi.jpg"}];

json.forEach(function(object, index){
 console.log('Index ==>' + index, ' Object data' + object);
 //or specific key value of object
 console.log(object.album_name);
});

答案 1 :(得分:0)

你也可以尝试这个

   $.each(json, function(i, obj) {  
      $.each(obj, function(index, value){
        console.log(index);
      });
  });

这是jsfiddle