How to set a Javascript object values dynamically?

Umut KIRGÖZ picture Umut KIRGÖZ · Jun 22, 2011 · Viewed 283.5k times · Source

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?

Answer

Matt Greer picture Matt Greer · Jun 22, 2011
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.