我想创建一个对象,有条件地添加成员。 简单的方法是:

var a = {};
if (someCondition)
    a.b = 5;

现在,我想写一个更习惯的代码。我在努力:

a = {
    b: (someCondition? 5 : undefined)
};

但是现在,b是a的一个元素,它的值是未定义的。这不是我们想要的结果。

有没有方便的解决办法?

更新

我寻求一个解决方案,可以处理一般情况与几个成员。

a = {
  b: (conditionB? 5 : undefined),
  c: (conditionC? 5 : undefined),
  d: (conditionD? 5 : undefined),
  e: (conditionE? 5 : undefined),
  f: (conditionF? 5 : undefined),
  g: (conditionG? 5 : undefined),
 };

当前回答

有条件地向对象添加成员

const trueCondition = true;
const falseCondition = false;
const obj = {
  ...(trueCondition && { student: 10 }),
  ...(falseCondition && { teacher: 2 }),
};

// { student: 10 }

其他回答

使用增强对象属性并只设置为真值的属性,例如:

[isConditionTrue() && 'propertyName']: 'propertyValue'

因此,如果条件不满足,它不会创建首选属性,因此您可以丢弃它。 见:http://es6-features.org/ ComputedPropertyNames

更新: 最好遵循Axel Rauschmayer在他的博客文章中关于在对象字面量和数组中有条件地添加条目的方法(http://2ality.com/2017/04/conditional-literal-entries.html):)

const arr = [
  ...(isConditionTrue() ? [{
    key: 'value'
  }] : [])
];

const obj = {
  ...(isConditionTrue() ? {key: 'value'} : {})
};

对我帮助很大。

我希望这有助于解决你的问题

身体< > <标题> GeeksforGeeks h1 > < / < p id =“极客”> < / p > < !——检查数组包含的脚本 对象与否——> <脚本> Var obj = {"geeks1":10, "geeks2":12} Var arr = ["geeks1", "geeks2", "geeks3", obj]; 如果(加勒比海盗。过滤器(值= = = >价值obj)。长度> 0) document . write(“true”); 其他的 document . write(“false”); > < /脚本 身体< / >

这是我能想到的最简洁的解决方案:

var a = {};
conditionB && a.b = 5;
conditionC && a.c = 5;
conditionD && a.d = 5;
// ...
const obj = {
   ...(condition) && {someprop: propvalue},
   ...otherprops
}

现场演示:

Const obj = { (true) && {someprop: 42}, …(false) && {nonprop: "foo"}, …({})&&{狡猾的:"hello"}, } console.log (obj);

我认为@InspiredJW用ES5做到了,正如@trincot指出的那样,使用es6是更好的方法。但我们可以添加更多的糖,通过使用扩散运算符,和逻辑与短路计算:

const a = {
   ...(someCondition && {b: 5})
}