Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, how to conditionally add a member to an object?

Tags:

javascript

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. 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),  }; 
like image 392
viebel Avatar asked Jul 28 '12 20:07

viebel


People also ask

How do you add a property to an object in JavaScript?

To add a new property to a Javascript object, define the object name followed by the dot, the name of a new property, an equals sign and the value for the new property.

How do you check if an object has a specific property in JavaScript?

We can check if a property exists in the object by checking if property !== undefined . In this example, it would return true because the name property does exist in the developer object.


1 Answers

I think @InspiredJW did it with ES5, and as @trincot pointed out, using es6 is a better approach. But we can add a bit more sugar, by using the spread operator, and logical AND short circuit evaluation:

const a = {    ...(someCondition && {b: 5}) } 
like image 116
Jamie Hill Avatar answered Dec 09 '22 11:12

Jamie Hill