Search code examples
javascriptobjectpropertiesset

How to set a Javascript object values dynamically?


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?


Solution

  • 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.