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

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

当前回答

您可以无条件地添加所有未定义的值,然后使用JSON。Stringify将它们全部删除:

const person = {
  name: undefined,
  age: 22,
  height: null
}

const cleaned = JSON.parse(JSON.stringify(person));

// Contents of cleaned:

// cleaned = {
//   age: 22,
//   height: null
// }

其他回答

有条件地向对象添加成员

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

// { student: 10 }

我更喜欢,使用代码这个吧,你可以运行这个代码

const three = {
  three: 3
}

// you can active this code, if you use object `three is null`
//const three = {}

const number = {
  one: 1,
  two: 2,
  ...(!!three && three),
  four: 4
}

console.log(number);
const obj = {
   ...(condition) && {someprop: propvalue},
   ...otherprops
}

现场演示:

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

我会这样做

var a = someCondition ? { b: 5 } : {};

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

身体< > <标题> 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”); > < /脚本 身体< / >