0

Supposte to have an object:

var obj = { 'home':1, 'dog':1, 'house':3 }

and suppose to have a variable

var variable='home';

(I don't know if it is possibile)

Now I need access to object in this way obj.variable so variable=home and it seems to do obj.home. I can do something like this? Anyone can help me?

1
  • Use bracket notation to access the key of the object which is dynamic.. obj[variable] Commented May 4, 2016 at 10:54

6 Answers 6

1

Try this obj[variable] to access value in json object.

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

Comments

0

Quite easy:

var obj = {'home':1,'dog':1,'house'};
var variable = 'home';

obj[variable] // prints 1

It's called property accessor.

Comments

0

You can access object properties with 2 ways:

  1. With . notation.
  2. With [] notation.

If your object property names are of reserved words or contain empty space, then you can't use . to access them. The only way to access them is [].

So you can access your object property as follows:

obj[variable] = 10 // or whatever value you wants to assign to this variable

Comments

0

Setting up the Object:

// Setting up Object
var obj = {
    home: 1,
    dog: 1,
    house: "big"
}

// Accesing object 
var home = obj.home;

or if you are dynamically generating go with:

// Setting up Object

var obj = {
    'home': '1',
    'dog': '1',
    'house': 'big'

}

// Accesing object 
var home = obj["home"];

Comments

0

You can access it using bracket notation like this obj[variable] which has the benefit that the string does not have to be a valid identifier; it can have any value, e.g. "1foo", "!bar!", or even " " (a space).

Comments

0

You can use obj[variable] like so:

var obj={'home':1,'dog':1,'house':5};
var variable='home';
obj[variable];

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.