2013-05-16 95 views
0

下面是名为data的嵌套对象。在这里我想显示所有的对象键和值。对于我已经写了代码,低于:如何访问另一个对象内的对象?

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

使用下面的代码我已经达到访问对象交易的“ID”这是关键,它的值是1,但给人的翻译:颜色,因为它有它自己的键和值,例如id:608290。我也想展示它。请对代码进行一些更改,以获取交易中颜色对象的该键和值。

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

'meta.response.deals'是一个数组吗? –

+0

是:'deals:[{id:1,color:{id:608290}}]'。它是一组对象。 – Broxzier

+0

你的问题很混乱。你的对象图是'metal.deals'还是'meta.response.deals'? –

回答

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

+0

Broxzier tnx但我想保持循环内的变化可以ü请你做 – king

+0

我看到你更新了数据对象,一会儿。 – Broxzier

+0

@king已更新的答案。 – Broxzier

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

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

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


}); 
}); 

感谢,

湿婆

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