How to refer to object fields with a variable?

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.


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

Tags:

Javascript