2013-06-12 519 views
1

我正在處理方法代碼,我必須通過動態數組遍歷一個json對象。我的代碼是這樣的:從數組中檢索對象的值

var tableHeaders = ["id", "name", "status"];  
var item = { 
    id: 1, 
    name: "test name", 
    status: true, 
    email: "[email protected]" 
}  
console.log(item.id); // works well --> 1  
console.log(tableHeaders[0]); // works well --> id  
console.log(item.tableHeaders[0]); // not works 

這裏的jsfiddle:http://jsfiddle.net/kslagdive/rjFHV/ 請給我建議,我怎麼能得到項目的價值與數組元素?由於

回答

2

由於您的屬性名是動態的,你必須使用bracket notation而不是dot notation

console.log(item[tableHeaders[0]]); // Works. 
+0

非常感謝。有用!!!! – KSL

1

它應該是...

item[ tableHeaders[0] ]; 

...也就是說,使用bracket notation到通過其名稱訪問屬性。請注意,您使用任何複雜的表達式這裏,例如:

item[ 'e' + 'mail' ]; // the same as item.email 
+0

是的。使用括號表示而不是點來表示它。謝謝。 – KSL

1

需要使用的,而不是.符號[]符號,當您使用動態密鑰

console.log(item[tableHeaders[0]]); 

演示:Fiddle

+0

使用括號表示而不是點來表示它。謝謝。 – KSL

0

Tabheaders不項目的值。嘗試

var tableHeaders = ["id", "name", "status"];  
var item = { 
    id: 1, 
    name: "test name", 
    status: true, 
    email: "[email protected]", 
    tableHeaders: tableHeaders // define "tableHeaders" as value of "item" 
} 

感謝@xec您的評論。

那麼答案已經在這裏了,但無論如何:

var key = tableHeaders[0]; // the key for the value you want to extract from items. 
var value = item[key];  // get the value from item based on the key defined 
          // in table headers using the [Bracket notation][1] 
          // (@Frédéric Hamidi). 
+2

我相信他希望'1'返回('id'屬性的值) – xec