使用变量作为对象的属性名称 - Javascript [英] Using Variable for Property Name of Object - Javascript

查看:80
本文介绍了使用变量作为对象的属性名称 - Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看到了一些与此相关的答案,但没有人回答这个问题的主题版本。

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

请考虑以下内容:(linkto: jsfiddle

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


});

使用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
第一个:name2
2:对象
第一个:name3
3:对象
first :name4
长度:4

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

问题是我希望属性first成为值var first(即name..相反,结果将是:

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
名称:name11:对象
名称:name22:对象
名称:name3 3:对象
名称:name4长度:4

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

(linkto: jsfiddle

推荐答案

将变量设置为键名你必须使用括号表示法;

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

对不起它更详细:(

编辑;

在ES6中,您现在可以使用 computed-property-names ;

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

const key = 'name';
const value = 'james';

const obj = {
  [key]: value
};

这篇关于使用变量作为对象的属性名称 - Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆