How to set a Javascript object values dynamically?

2019-01-03 14:06发布

It's difficult to explain the case by words, let me give an example:

var myObj = {
    'name': 'Umut',
    'age' : 34
};

var prop = 'name';
var value = 'Onur';

myObj[name] = value; // This does not work

eval('myObj.' + name) = value;   //Bad coding ;)

How can I set a variable property with variable value in a JavaScript object?

6条回答
做自己的国王
2楼-- · 2019-01-03 14:20

You could also create something that would be similar to a value object (vo);

SomeModelClassNameVO.js;

function SomeModelClassNameVO(name,id) {
    this.name = name;
    this.id = id;
}

Than you can just do;

   var someModelClassNameVO = new someModelClassNameVO('name',1);
   console.log(someModelClassNameVO.name);
查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-03 14:21
myObj.name=value

or

myObj['name']=value     (Quotes are required)

Both of these are interchangeable.

Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/

查看更多
小情绪 Triste *
4楼-- · 2019-01-03 14:31
myObj[prop] = value;

That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.

查看更多
Viruses.
5楼-- · 2019-01-03 14:34

simple as this myObj.name = value;

查看更多
仙女界的扛把子
6楼-- · 2019-01-03 14:40

When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.

You can access these dictionaries in two ways:

  • Like an array (e.g. myObj[name]); or
  • Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.

You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.

myObj["name"]

Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.

查看更多
▲ chillily
7楼-- · 2019-01-03 14:44

You can get the property the same way as you set it.

foo = {
 bar: "value"
}

You set the value foo["bar"] = "baz";

To get the value foo["bar"]

will return "baz".

查看更多
登录 后发表回答