Is it possible to add dynamically named properties to JavaScript object?

后端 未结 19 1520
攒了一身酷
攒了一身酷 2020-11-21 05:39

In JavaScript, I\'ve created an object like so:

var data = {
    \'PropertyA\': 1,
    \'PropertyB\': 2,
    \'PropertyC\': 3
};

Is it poss

19条回答
  •  醉话见心
    2020-11-21 06:07

    ES6 for the win!

    const b = 'b';
    const c = 'c';
    
    const data = {
        a: true,
        [b]: true, // dynamic property
        [`interpolated-${c}`]: true, // dynamic property + interpolation
        [`${b}-${c}`]: true
    }
    

    If you log data you get this:

    {
      a: true,
      b: true,
      interpolated-c: true,
      b-c: true
    }
    

    This makes use of the new Computed Property syntax and Template Literals.

提交回复
热议问题