1

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

asked Jun 12, 2013 at 7:33

4 Answers 4

2

Since your property name is dynamic, you have to use bracket notation instead of dot notation:

console.log(item[tableHeaders[0]]); // Works.
answered Jun 12, 2013 at 7:35
Sign up to request clarification or add additional context in comments.

Comments

1

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
answered Jun 12, 2013 at 7:35

1 Comment

Yes okay. Got it using bracket notation instead of dot. Thanks.
1

Need to use [] notation instead of . notation when you use dynamic keys

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

Demo: Fiddle

answered Jun 12, 2013 at 7:35

1 Comment

Got it using bracket notation instead of dot. Thanks.
0

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).
answered Jun 12, 2013 at 7:36

1 Comment

I believe he wants 1 returned (the value of the id property)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.