How to use a variable for a key in a JavaScript ob

2018-12-30 22:05发布

Why does the following work?

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

Whereas this doesn't work:

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

To make it even clearer: At the moment I'm not able to pass a CSS property to the animate function as a variable.

9条回答
残风、尘缘若梦
2楼-- · 2018-12-30 22:56

Given code:

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

Translation:

var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);

As you can see, the { thetop : 10 } declaration doesn't make use of the variable thetop. Instead it creates an object with a key named thetop. If you want the key to be the value of the variable thetop, then you will have to use square brackets around thetop:

var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);

The square bracket syntax has been introduced with ES6. In earlier versions of JavaScript, you would have to do the following:

var thetop = 'top';
var config = (
  obj = {},
  obj['' + thetop] = 10,
  obj
); // config.top = 10
<something>.stop().animate(config, 10);
查看更多
像晚风撩人
3楼-- · 2018-12-30 23:03

ES5 implementation to assign keys is below:

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

Object.defineProperties(obj, objArgs);

I've attached a snippet I used to convert to bare object.

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

查看更多
查无此人
4楼-- · 2018-12-30 23:07

Adding square bracket around the variable works good for me. Try this

var thetop = 'top';
<something>.stop().animate(
    { [thetop] : 10 }, 10
);
查看更多
登录 后发表回答