Using Variable for Property Name of Object - Javas

2020-02-14 10:23发布

问题:

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)

回答1:

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
};


回答2:

var x = {}
x[first] = value
objArr[key] = x

Javascript object literal syntax treats unquoted keys as if they were quoted strings instead of variable names. You have to use bracket syntax to set properties with names computed at runtime.

(Why are you wrapping your code in a jQuery call? And you really should be using var declarations.)