Reputation: 49
I am working on method code in which I have to iterate through an json object with dynamic array. my code is like this:
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
Here is jsfiddle: http://jsfiddle.net/kslagdive/rjFHV/ Please suggest me, how can I get value of item with Array element? Thanks
Upvotes: 1
Views: 71
Reputation: 14893
Tabheaders is not a value of item. Try
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"
}
Thanks @xec for your comment.
Well the answer is already here but anyway:
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).
Upvotes: 0
Reputation: 388436
Need to use []
notation instead of .
notation when you use dynamic keys
console.log(item[tableHeaders[0]]);
Demo: Fiddle
Upvotes: 1
Reputation: 106483
It should be...
item[ tableHeaders[0] ];
... that is, using bracket notation to access a property by its name. Note that you use any complex expression here, for example:
item[ 'e' + 'mail' ]; // the same as item.email
Upvotes: 1
Reputation: 263147
Since your property name is dynamic, you have to use bracket notation instead of dot notation:
console.log(item[tableHeaders[0]]); // Works.
Upvotes: 2