0

I'm new to javascript. I have a strange requirement.

How can we access the value of an object whose key is the value of another object?

Ex:

Obj1 = {"name":"John", "age":30, "car":null};
Obj2 = {"John":{"country":"america", "job":"Engineer"}}

How to achieve something like Obj2.{Obj1.name}.country (result: america)

3 Answers 3

2

Just use bracket notation like so:

Obj1 = {"name":"John", "age":30, "car":null};
Obj2 = {"John":{"country":"america", "job":"Engineer"}}

Obj2[Obj1.name].country;
// or
Obj2[Obj1["name"]]["country"]
Sign up to request clarification or add additional context in comments.

Comments

1

You can access object properties using the square bracket syntax.

object.property is equal to object["property"].

For your example, you can do

console.log(Obj2[Obj1.name]);

Comments

1

You can try the following Obj2[Obj1['name']]['country']

Comments

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.