最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Real use case dynamic (computed) property - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Jan 11, 2016 at 18:16 LaoujinLaoujin 10.2k7 gold badges45 silver badges72 bronze badges 4
  • 1 could it not be used to calculate a value of a property which represents the price + tax or similar? – Sam Holder Commented Jan 11, 2016 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. – Ruan Mendes Commented Jan 11, 2016 at 18:24
  • 1 Have a look at our canonical Using a variable for a key in a JavaScript object literal and all its linked questions for an overview of use cases – Bergi Commented Jan 11, 2016 at 18:33
  • Okay... And now I just used it myself:) { [match.isHomeMatch ? 'home' : 'away']: own(), [match.isHomeMatch ? 'away' : 'home']: theirs() } – Laoujin Commented Feb 9, 2016 at 2:15
Add a comment  | 

5 Answers 5

Reset to default 9

If you have a property name as a constant:

var obj = { [SOME_CONSTANT]: 42 };

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

You can use it in class and with Symbols:

class MyClass {
    [Symbol.iterator]() {
        // my iterator
    }
}

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
}

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

发布评论

评论列表(0)

  1. 暂无评论