how.wtf

Conditionally add properties to an object in JavaScript

· Thomas Taylor

Conditionally adding properties/fields/members to an object in JavaScript or TypeScript can be completed using a combination of the logical and spread operators or simply an if statement.

Add conditional properties using if

A simple technique is using an if statement to conditionally add members:

1let obj = {}
2if (condition)
3  obj.field = 5;

There are no thrills to this technique, but it’s straight forward.

Add conditional properties using logical and spread operators

For a shorter syntax, ES5 introduced the ability to do this:

1const obj = {
2  ...(condition && {field: 5})
3}

This technique works due to how logical operators function in JavaScript.

1console.log(true && {field: 5})

The snippet above is processed as follows: starting from left and traversing right, the first operand that is evaluated as falsy is returned. In the expression above, there are no falsy operands so the right-most is returned.

The output:

1{field: 5}

Additionally, the spread operator has a lower precedence than the && operator because the underlying implementation uses Object.assign()

If the condition is false:

1const obj = {
2  val: 2,
3  ...(false && {field: 5})
4}
5console.log(obj)

The spread operation will be result in nothing being added.

1{val:2}

#Javascript  

Reply to this post by email ↪