How to use a computed property name in ES5?

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.


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)