如何访问另一个对象内的对象?

时间:2013-05-16 09:59:42

标签: javascript jquery

下面是名为data的嵌套对象。在这里,我想显示所有对象键和值。为此我写了一个代码如下:

var data = {
       response: {
           deals: [
                    {
                    id: 1,
                    color: {
                          id: 608290
                       }
                    }
                 ]
              }
          };

使用下面的代码,我已经访问了对象交易的“id”,它是密钥,其值为1,但为[color object]提供了颜色,因为它有自己的密钥和值,即id:608290。我也想显示它。请对代码进行一些更改,以获得该关键字以及交易中颜色对象的值。

for(var i = 0; i <= data.response.deals.length-1;i++){
    $.each( meta.response.deals[i], function( key, value ) {
        alert( key + ": " + value );
});

5 个答案:

答案 0 :(得分:1)

此代码将贯穿对象的数组。在循环中,你可以做任何你想做的交易。

var data = {
    response: {
        deals: [{
            id: 1,
            color: { id: 608290 }
        },
        {   id: 2,
            color: { id: 123456 }
        },
        {   id: 9001,
            color: { id: 456789 }
        }]
    }
};

for (var i in data.response.deals) {
    var obj = data.response.deals[i];
    console.log(obj);

    // obj.id       => current ID
    // obj.color.id => color's ID
}

日志:

{"color": {"id": 608290}, "id": 1}
{"color": {"id": 123456}, "id": 2}
{"color": {"id": 456789}, "id": 9001}

实例:http://jsbin.com/ipeful/4

答案 1 :(得分:0)

$.each(data.metal.deals,function(i,item){

        // alert("id:"+item.id+" color:"+item.color.id);

});

答案 2 :(得分:0)

var data = { metal: { deals: [ { id: 1, color: { id: 608290 } } ] } };

$.each(metal.deals,function(index,item){

 $.each(item,function(itemIndex,value)
{
//process your sub items


});
});

谢谢,

希瓦

答案 3 :(得分:0)

试试这个

        $.each(data.response.deals, function(index, item)
        {
            //item is the object you have in the array
            //item.id ==> The id value in the object
            //item.color.id ==> The id value in the color object
        });

答案 4 :(得分:0)

您可以使用这样的递归函数:

function deepTraverse(obj, indent) {
    var str = "";
    for (var key in obj) {
        var newIndent = indent + "&nbsp;&nbsp;&nbsp;&nbsp;";     // <-- for formatting only
        str += newIndent + key + ": ";
        str += (typeof obj[key] != "object")
                ? obj[key] + "<br />"
                : "<br />" + deepTraverse(obj[key], newIndent);
        if (typeof obj[key] != "object") {
            alert(key + ": " + obj[key]);
        }
    }
    return str;
}

另请参阅此 short demo

相关问题