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?
You could also create something that would be similar to a value object (vo);
SomeModelClassNameVO.js;
Than you can just do;
or
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/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.
simple as this
myObj.name = value;
When you create an object
myObj
as you have, think of it more like a dictionary. In this case, it has two keys,name
, andage
.You can access these dictionaries in two ways:
myObj[name]
); ormyObj.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.
Otherwise, javascript will assume that
name
is a variable, and since you haven't created a variable calledname
, it won't be able to access the key you're expecting.You can get the property the same way as you set it.
You set the value
foo["bar"] = "baz";
To get the value
foo["bar"]
will return "baz".