Using Variable for Property Name of Object - Javascript [duplicate]

雨燕双飞 提交于 2019-11-28 09:41:36

问题


This question already has an answer here:

  • How to use the value of a variable in creating an object in JavaScript [duplicate] 1 answer

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



来源:https://stackoverflow.com/questions/17254187/using-variable-for-property-name-of-object-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!