17

Let's asume that I have an object:

var obj = {"A":"a", "B":"b", "x":"y", "a":"b"} 

When I want to refer to "A" I just write obj.A

How to do it when I have key in a variable, i.e.:

var key = "A"; 

Is there any function that returns a value or null (if key isn't in the object)?

0

2 Answers 2

29

Use bracket notation, like this:

var key = "A"; var value = json[key]; 

In JavaScript these two are equivalent:

object.Property object["Property"]; 

And just to be clear, this isn't JSON specific, JSON is just a specific subset of object notation...this works on any JavaScript object. The result will be undefined if it's not in the object, you can try all of this here.

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

1 Comment

+1. Note though that the two forms you mentioned are equivalent only if the Property is not a reserved word... of which there are many in JS, and quite a few are unexpected. So in that sense object["Property"] is safer. OTOH, object.Property has the advantage (when Property is known statically) that tools like JSLint can run checks on them.
3

How about:

json[key] 

Try:

json.hasOwnProperty(key) 

for the second part of your question (see Checking if a key exists in a JavaScript object?)

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.