如何在JavaScript对象字面量中使用变量作为键?

587

为什么以下代码有效?

<something>.stop().animate(
    { 'top' : 10 }, 10
);

然而,这个并不起作用:

var thetop = 'top';
<something>.stop().animate(
    { thetop : 10 }, 10
);
为了更清楚地表达:目前我无法将CSS属性作为变量传递给动画函数。

2
参见:使用动态键创建对象 - Bergi
谢谢。我正在搜索确切的东西。 - Siva-Dev-Wizard
这个回答解决了你的问题吗?JavaScript通过变量设置对象键 - Abdul Aziz Barkat
16个回答

2

2020更新/示例...

一个更复杂的示例,使用括号和字面量...这是你可能需要用vue/axios做的事情。将字面量放在括号中,如下所示:

[ ` ... ` ]

{
    [`filter[${query.key}]`]: query.value,  // 'filter[foo]' : 'bar'
}

0

以下是分配键的ES5实现:

var obj = Object.create(null),
    objArgs = (
      (objArgs = {}),
      (objArgs.someKey = {
        value: 'someValue'
      }), objArgs);

Object.defineProperties(obj, objArgs);

我附上了一个代码片段,用于将其转换为裸对象。

var obj = {
  'key1': 'value1',
  'key2': 'value2',
  'key3': [
    'value3',
    'value4',
  ],
  'key4': {
    'key5': 'value5'
  }
}

var bareObj = function(obj) {

  var objArgs,
    bareObj = Object.create(null);

  Object.entries(obj).forEach(function([key, value]) {

    var objArgs = (
      (objArgs = {}),
      (objArgs[key] = {
        value: value
      }), objArgs);

    Object.defineProperties(bareObj, objArgs);

  });

  return {
    input: obj,
    output: bareObj
  };

}(obj);

if (!Object.entries) {
  Object.entries = function(obj){
    var arr = [];
    Object.keys(obj).forEach(function(key){
      arr.push([key, obj[key]]);
    });
    return arr;
  }
}

console(bareObj);


0
如果您想让对象键与变量名相同,在 ES 2015 中有一个简写方法。 ECMAScript 2015 中的新符号
var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10

0
你可以这样做:
var thetop = 'top';
<something>.stop().animate(
    new function() {this[thetop] = 10;}, 10
);

-1

对于ES5,你可以这样做:

var theTop = 'top'
<something>.stop().animate(
  JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10
)

或者提取到一个函数中:

function newObj (key, value) {
  return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')
}

var theTop = 'top'
<something>.stop().animate(
  newObj(theTop, 10), 10
)

-1

这样你也可以实现所需的输出

var jsonobj={};
var count=0;
$(document).on('click','#btnadd', function() {
    jsonobj[count]=new Array({ "1"  : $("#txtone").val()},{ "2"  : $("#txttwo").val()});
    count++;
    console.clear();
    console.log(jsonobj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>value 1</span><input id="txtone" type="text"/>
<span>value 2</span><input id="txttwo" type="text"/>
<button id="btnadd">Add</button>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接