2013-05-16 106 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