Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer to object fields with a variable? [duplicate]

Tags:

javascript

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

like image 727
liysd Avatar asked Aug 23 '10 12:08

liysd


2 Answers

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.

like image 58
Nick Craver Avatar answered Oct 24 '22 22:10

Nick Craver


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

like image 30
Bobby Jack Avatar answered Oct 24 '22 20:10

Bobby Jack