How to use a computed property name in ES5?

2020-04-05 07:57发布

I would like to have a computed property name. I saw you can have this in ES6. But it should be compatible with IOS Webview. So I can't use ES6. Also the computed name will be ever the same inside the loop, if this makes it easier for somebody.

Any Ideas?

var today = moment().format('DD.MM.YY');
for (var i = 0; i < 5; i++) {
    initialData.push(
         {
            dates: {
                "01.01.01": false
                 // instead of 01.01.01 i would like to have the value of today as the key
            }
        }
    )
}

2条回答
爷、活的狠高调
2楼-- · 2020-04-05 08:56

You have to do it the elaborate way in ES5:

var today  = moment().format('DD.MM.YY');
var obj    = {};
obj[today] = false;
for (var i = 0; i < 5; i++) {
  initialData.push({ dates: obj });
}

(or move the creation of obj inside the loop if it's different for each iteration)

查看更多
欢心
3楼-- · 2020-04-05 09:00

If you happen to have code full of ES6+ syntax, such as computed property names, and you want to make it ES5 compatible, the easiest way by far would be to use a transpiler like Babel to do it for you automatically. This will allow you to write your source code in the latest and most readable version of the language while permitting obsolete browsers to understand the transpiled code, without having to mess with ugly and verbose ES5 syntax yourself.

For example, if you had source code that looks like this that you wanted to make ES5 compatible:

const prop1 = 'foo';
const prop2 = 'bar';
const prop3 = 'baz';
const obj = {
  [prop1]: 'val1',
  [prop2]: 'val2',
  [prop3]: 'val3',
};

console.log(obj);

You can run it through Babel and automatically get the ES5 version:

"use strict";

var _obj;

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}

var prop1 = "foo";
var prop2 = "bar";
var prop3 = "baz";
var obj = ((_obj = {}),
_defineProperty(_obj, prop1, "val1"),
_defineProperty(_obj, prop2, "val2"),
_defineProperty(_obj, prop3, "val3"),
_obj);
console.log(obj);

The transpiled code might look a bit ugly, but most of the time, you don't even need to look at it, just serve it to clients and it'll work, even on obsolete environments like Internet Explorer.

查看更多
登录 后发表回答