3

I am working on the following snippet. Why am I not able to get the

let node = 'Em2'; console.log(data.node.c2); 

work? As you can see I am able to get data while passing data.Em2.c1 but a dynamic format like this let node = 'Em2'; console.log(data.node.c2); I am getting this error

TypeError: Cannot read property 'c2' of undefined

Code:

var data ={ "Em1": { "c1":"#FFF", "c2":"#EEE" }, "Em2": { "c1":"#DDD", "c2":"#ooo" } } let node = 'Em2'; console.log(data.Em2.c1); console.log(data.node.c2); 

var data ={ "Em1": { "c1":"#FFF", "c2":"#EEE" }, "Em2": { "c1":"#DDD", "c2":"#ooo" } } let node = 'Em2'; console.log(data.Em2.c1); console.log(data.node.c2);

0

2 Answers 2

2

Use square braces [] to access object member via variable

var data ={ "Em1": { "c1":"#FFF", "c2":"#EEE" }, "Em2": { "c1":"#DDD", "c2":"#ooo" } } let node = 'Em2'; console.log(data.Em2.c1); console.log(data[node].c2);

Similar question: how to access object property using variable

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Alex but why [] ?!
@Mona if you don't use square braces, js tries to use named property node in your object, not property named in variable node
0

Instead of console.log(data.node.c2), try console.log(data[node][c2])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.