Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

javascript - 在Javascript中,如何有条件地将成员添加到对象?(In Javascript, how to conditionally add a member to an object?)

I would like to create an object with a member added conditionally.

(我想创建一个有条件添加成员的对象。)

The simple approach is:

(简单的方法是:)

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

Now, I would like to write a more idiomatic code.

(现在,我想编写一个更惯用的代码。)

I am trying:

(我在尝试:)

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

But now, b is a member of a whose value is undefined .

(但现在, b是一个成员a ,其值是undefined 。)

This is not the desired result.

(这不是期望的结果。)

Is there a handy solution?

(有方便的解决方案吗?)

Update

(更新资料)

I seek for a solution that could handle the general case with several members.

(我寻求一个可以解决几个成员的一般情况的解决方案。)

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),
 };
  ask by viebel translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think @InspiredJW did it with ES5, and as @trincot pointed out, using es6 is a better approach.

(我认为@InspiredJW是使用ES5完成的,正如@trincot指出的那样,使用es6是更好的方法。)

But we can add a bit more sugar, by using the spread operator, and logical AND short circuit evaluation:

(但是,通过使用散布运算符和逻辑与短路评估,我们可以添加更多的糖:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...