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

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

当前回答

var a = {
    ...(condition ? {b: 1} : '') // if condition is true 'b' will be added.
}

我希望这是基于条件添加条目的更有效的方法。 有关如何有条件地在对象字面量中添加条目的详细信息。

其他回答

为了完整起见,如果您想添加额外的描述符,可以使用Object.defineProperty()。注意,我特意添加了enumerable: true,否则该属性不会出现在console.log()中。这种方法的优点是,如果你想添加多个新属性,你也可以使用Object.defineProperties()(然而,这样每个属性都依赖于相同的条件…)

const select = document.getElementById("condition"); const output = document.getElementById("output"); let a = {}; let b = {}; select.onchange = (e) => { const condition = e.target.value === "true"; condition ? Object.defineProperty(a, "b", { value: 5, enumerable: true, }) : (a = {}); condition ? Object.defineProperties(b, { c: { value: 5, enumerable: true, }, d: { value: 6, enumerable: true, }, e: { value: 7, enumerable: true, }, }) : (b = {}); outputSingle.innerText = JSON.stringify(a); outputMultiple.innerText = JSON.stringify(b); }; Condition: <select id="condition"> <option value="false">false</option> <option value="true">true</option> </select> <br/> <br/> Single Property: <pre id="outputSingle">{}</pre><br/> Multiple Properties: <pre id="outputMultiple">{}</pre>

用let定义一个变量,然后赋值一个新属性

let msg = {
    to: "hito@email.com",
    from: "hifrom@email.com",
    subject: "Contact form",    
};

if (file_uploaded_in_form) { // the condition goes here
    msg.attachments = [ // here 'attachments' is the new property added to msg Javascript object
      {
        content: "attachment",
        filename: "filename",
        type: "mime_type",
        disposition: "attachment",
      },
    ];
}

现在味精变成了

{
    to: "hito@email.com",
    from: "hifrom@email.com",
    subject: "Contact form",
    attachments: [
      {
        content: "attachment",
        filename: "filename",
        type: "mime_type",
        disposition: "attachment",
      },
    ]
}

在我看来,这是一个非常简单易行的解决方案。

如果你想做这个服务器端(不使用jquery),你可以使用lodash 4.3.0:

a = _.pickBy({ b: (someCondition? 5 : undefined) }, _.negate(_.isUndefined));

这是使用lodash 3.10.1实现的

a = _.pick({ b: (someCondition? 5 : undefined) }, _.negate(_.isUndefined));

更简化,

const a = {
    ...(condition && {b: 1}) // if condition is true 'b' will be added.
}

简单的es6解决方案

带有(&)的单一条件

const didIPassExam = true Const study = { 星期一:“写作”, 周二:“阅读”, /*有条件检查,如果为真,则增加周三学习*/ ...(didIPassExam &&{星期三:'睡得开心'}) } console.log(研究)

带有(?):)

Const分数= 110 //const得分= 10 Const storage = { 答:10 b: 20, ...(得分> 100 ?{c: 30}: {d:40}) } console.log(存储)

解释

假设你有一个这样的存储对象

const storage = {
  a : 10,
  b : 20,
}

你想在此基础上有条件地增加一个道具

const score = 90

如果分数大于100,您现在希望将道具c:30添加到存储区。

如果score小于100,则需要将d:40添加到存储中。你可以这样做

const score = 110

const storage = {
  a:10,
  b:20,
  ...(score > 100  ? {c: 30} : {d:40}) 
}

上面的代码给出存储为

{
  a: 10,
  b: 20,
  c: 30
}

如果分数= 90

然后你得到存储

{
  a: 10,
  b: 20,
  d: 40
}

Codepen例子