Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real use case dynamic (computed) property

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?

like image 539
Laoujin Avatar asked Jan 11 '16 18:01

Laoujin


2 Answers

If you have a property name as a constant:

var obj = { [SOME_CONSTANT]: 42 };
like image 167
SLaks Avatar answered Oct 17 '22 19:10

SLaks


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,
    ...
));
like image 6
Juan Mendes Avatar answered Oct 17 '22 19:10

Juan Mendes