简体   繁体   中英

How access to object with value of a variable

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?

尝试使用此obj[variable]访问json对象中的值。

Quite easy:

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

obj[variable] // prints 1

It's called property accessor .

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

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"];

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, eg "1foo", "!bar!", or even " " (a space).

You can use obj[variable] like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM