使用$ .each获取json数组对象值

时间:2015-05-28 09:34:09

标签: javascript jquery json

This是我的JSON的结构:

[{
    "industry": [{
        "Supermart": [{
            "merchant": [{
                "name": "Lazada",
                "banner": "abc.com/img.jpg",
                "url": "http://lazada.com.my"
            }]
        }]
    }, {
        "apparel": [{
            "merchant": [{
                "name": "fashionvalet",
                "banner": "https://pbs.twimg.com/profile_images/572008219506003968/SEB35DFb.png",
                "url": "http://lazada.com.my"
            }]
        }]
    }, {
        "Electronics": [{
            "merchant": [{
                "name": "Rakuten",
                "banner": "http://kpisland.com/wp-content/uploads/2013/05/RakutenMalaysia.jpg",
                "url": "http://www.rakuten.com.my/"
            }]
        }]
    }]
}]

如何获得行业数组obj值?比如supermartapperalelectronics

//ajax callback
success: function (data) {
    data = JSON.parse(data);

    $.each(data.industry, function (index, obj) {
        console.log(this[index][0]);
    });
},
error: function () { 
});

我试过console.log(this[index])它返回undefined,或者我的json结构错了?

2 个答案:

答案 0 :(得分:0)

数据是一个数组data[0].industry

$.each(data[0].industry, function (index, obj) {
    var key = Object.keys(obj)[0];
    console.log('Key',key);
});

演示:Fiddle

答案 1 :(得分:0)

你必须使用

data.industry[index]

或只是obj返回值。