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

Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264
liysd
  • 4,103
  • 12
  • 34
  • 38

2 Answers2

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.

Nick Craver
  • 610,884
  • 134
  • 1,288
  • 1,151
  • +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. – LarsH Aug 23 '10 at 16:17
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?)

Community
  • 1
  • 1
Bobby Jack
  • 15,215
  • 11
  • 61
  • 96