【问题标题】:JavaScript insert a new property to inline object only if condition is met [duplicate]仅当满足条件时,JavaScript才会将新属性插入内联对象[重复]
【发布时间】:2020-06-16 06:26:28
【问题描述】:

我知道对于 ES6 JavaScript 对象,您可以使用 [] 将变量动态声明为对象键,例如:

{[2 + 2]: "four!"}

给出输出{"4": "four!"}

问题是,是否可以使用类似的方法通过变量等内联添加整个属性?意思是,假设我有以下测试对象:

var myObj = {
    someProp: 2,
    someOtherProp: 3 //only add this prop if a condition is met
}

我可以在someOtherProp 的内联对象中写什么,只有在满足特定条件时才将其添加到对象中?所以例如(伪代码),像这样的东西

var myObj = {
    someProp: 2,
    [someBool ? null : "someOtherProp: 3"] //only add this prop if a condition is met
}

会给出输出(考虑到 someBool 是真的),就像上面一样,但是如果 someBool 是假的,它会给我

var myObj = {
    someProp: 2
}

??

我知道我可以稍后使用 [] 索引器向(/从)对象简单地添加(或删除)属性,例如

someBool && (myObj["someOtherProp"] = 3)

以及为此制作某种辅助函数,

但我想知道是否有办法使用内联对象表示法?

【问题讨论】:

标签: javascript object indexing ecmascript-6


【解决方案1】:

您可以使用条件运算符传播对象。

{} 是一个中性值。

var myObj = {
    someProp: 2,
    ...(someBool ? {} : { someOtherProp: 3 })
}

【讨论】:

  • ...(someBool && { someOtherProp: 3}) 可能会更短
猜你喜欢
  • 2021-08-21
  • 1970-01-01
  • 2013-04-05
  • 2016-03-09
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多