Search code examples
javascriptjqueryobjectpropertiesvariable-variables

Using Variable for Property Name of Object - Javascript


saw a few answers related to this, but none answer this version of the subject in question.

Consider the following: (linkto: jsfiddle)

$(function(){

arrKeys = [];
objArr = [];

nameArr = ['name1','name2','name3','name4'];
descArr = ['desc1','desc2','desc3','desc4'];
allValues = {name:  nameArr, desc: descArr};

arrKeys[0] = 'name';
arrKeys[1] = 'desc';

    first = arrKeys.shift(); // returns 'name'

    $(allValues[first]).each(function (key,value) { 

        console.log(first); //returns 'name'
        objArr[key] = {first:value}; //the problem

    });

    console.log(objArr);


});

With console.log(objArr) producing the following array of objects like so:

[Object, Object, Object, Object] 0: Object first: "name1" 1: Object first: "name2" 2: Object first: "name3" 3: Object first: "name4" length: 4

The issue is that I'd like the property "first" to be the value of the var first (which is "name".. So instead, the result would be:

[Object, Object, Object, Object] 0: Object name: "name1" 1: Object name: "name2" 2: Object name: "name3" 3: Object name: "name4" length: 4

(linkto: jsfiddle)


Solution

  • To set variables as key names you have to use bracket notation;

    console.log(first); // returns 'name'
    var obj = {};
    obj[first] = value;
    objArr[key] = obj; // no longer a problem
    

    Sorry it's more verbose :(

    Edit;

    In ES6 you can now use computed-property-names;

    const key = 'name';
    const value = 'james';
    
    const obj = {
      [key]: value
    };