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

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.
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

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

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).

1 Comment

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

Your Answer

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.