Search code examples
javascriptobjectsyntaxparametersnotation

How to add property to object using bracket notation for object and string for property name?


I would like to use bracket notation for writing the object name so that I can reference it via a parameter. That's fine, but I run into trouble when I try to write the property name without passing it as a parameter. It's important that the property name is simply written out and not passed as a parameter. What is the correct syntax?

This example shows all of the syntax variations that I have tried:

var foo = {};

bar('foo', 'cat');
function bar(object, prop) {
    
    // foo[prop] = 5; // = 5. This works, but this isn't the method I want to use. 
    
    // [object]cat = 5; // = error
    // [object].cat = 5; // = undefined
    // [object]['cat'] = 5; // = undefined
    // [object][cat] = 5; // = error
    
    console.log('= ' + foo.cat);
}


Solution

  • As foo is declared as a global variable, the window object will contain that object internally.

    So, you can do the following:

    window[object]['cat'] = 5;
    

    var foo = {};
    
    bar('foo');
    console.log('= ' + foo.cat);
    function bar(object) {
        window[object]['cat'] = 5;            
    }