访问内部属性名称以在ES6中计算新属性

时间:2016-01-14 11:04:34

标签: javascript properties ecmascript-6

我有对象。我想添加属性,但我想在定义期间为Select [Inprogress], [Complete], [Printed] from (select specimenID, count([RStatus]) from tbl_LabReport group by specimenID) as sourcetable Pivot (Count(specimenID) for [RStatus] in ( [Inprogress],[Complete],[Printed] )) as ptv 中的所有属性计算suffix

object

以下是我的预期输出:

var myObject = {
    foo: "bar",
    [ "prop_" + "Access foo property: foo" ]: 42
};
  

事实并非如此,我无法实现它。我可以通过下面的片段及其工作正常来实现,但我希望在声明期间完成。

{
    foo: "bar",
    prop_bar: 42
}
  

审稿人注意事项:我已经审核了以下问题。

     
      
  1. Is there a shorthand for this in ES6/ES7?
  2.   
  3. ES6 Object Literal Property Value Shorthand
  4.   
  5. How to use ES6 computed property names in node / iojs?
  6.   
  7. ES6 Computed (dynamic) property names
  8.   

我觉得会有比上述方法更好的解决方案,下面是我的问题。

此方案的最佳方法是什么?

我们可以通过多少方式实现这一目标?

宣言期间不可能吗?

1 个答案:

答案 0 :(得分:1)

您可以创建工厂功能来执行此操作,例如:

const create = v => ({
    foo: v,
    ["prop_" + v]: 42
});
let myObject = create("bar");

或内联:

let myObject = (v => ({
    foo: v,
    ["prop_" + v]: 42
}))("bar");
相关问题