6

A dynamic property:

var obj = {
  // Computed (dynamic) property names
  [ 'prop_' + (() => 42)() ]: 42
};

This is of course very fancy. But where could someone use this without adding unnecessary complexity?

Laoujin
  • 9,438
  • 6
  • 36
  • 66
  • 1
    could it not be used to calculate a value of a property which represents the price + tax or similar? – Sam Holder Jan 11 '16 at 18:19
  • 1
    @SamHolder That would be a real dynamic property, but the OP is talking about dynamic property names, from the example in the question. – Juan Mendes Jan 11 '16 at 18:24
  • 1
    Have a look at our canonical [Using a variable for a key in a JavaScript object literal](http://stackoverflow.com/q/2274242/1048572) and all its linked questions for an overview of use cases – Bergi Jan 11 '16 at 18:33
  • Okay... And now I just used it myself:) `{ [match.isHomeMatch ? 'home' : 'away']: own(), [match.isHomeMatch ? 'away' : 'home']: theirs() }` – Laoujin Feb 09 '16 at 02:15

5 Answers5

9

If you have a property name as a constant:

var obj = { [SOME_CONSTANT]: 42 };
SLaks
  • 837,282
  • 173
  • 1,862
  • 1,933
6

One case where I wanted it was where property names for JSON were defined in generated files, based off Java classes.

// Generated
var SomeJsonBodyParams = {NAME: 'name', ID: 'id', ETA, 'estimatedTimeOfArrival'};

// Using it
sendAjax('some/url', {
    [SomeJsonBodyParams.NAME] = userData.name,
    ...
});

We even had a method so we could kind of do it

function makeObj() {
  var obj = {};
  for (var i=0; i < arguments.length; i+=2) {
      obj[i] = obj[i+i];
  }
  return obj;
}

sendAjax('some/url', makeObj(
    SomeJsonBodyParams.NAME, userData.name,
    ...
));
Juan Mendes
  • 85,853
  • 29
  • 146
  • 204
3

You can use it in class and with Symbols:

class MyClass {
    [Symbol.iterator]() {
        // my iterator
    }
}
madox2
  • 45,325
  • 15
  • 94
  • 95
2

Let's say you have:

var hi = 'hi';
var test = 'test';
var hello = 'hello';

Instead of:

var object = {};

object[hi] = 111;
object[test] = 222;
object[hello] = 333;

You could write it in a much shorter syntax:

var object = {
    [hi]: 111,
    [test]: 222,
    [hello]: 333
}
Jacques Marais
  • 2,586
  • 13
  • 33
1

E.g. it could be used when you want to use a, let's say, constant as a key in object.

const DATA_TYPE = {
    PERSON: 'person',
    COMPANY: 'company'
};

let cache = {
    [DATA_TYPE.PERSON]: getPerson()
};

And later access:

cache[DATA_TYPE.PERSON]

Instead of DATA_TYPE.PERSON could be anything (including some real-time calculated values).

Kiril
  • 2,865
  • 1
  • 36
  • 41