Skip to content

Latest commit

 

History

History
35 lines (26 loc) · 650 Bytes

conditionally-include-pairs-in-an-object.md

File metadata and controls

35 lines (26 loc) · 650 Bytes

Conditionally Include Pairs In An Object

You can add key-value pairs to an object using the ES6 spread operator:

> { one: 1, ...{ hello: "world" } }
{ one: 1, hello: "world" }

By combining the spread operator with some boolean logic, you can conditionally add key-value pairs to an object:

> {
    one: 1,
    ...(isArriving && { hello: "world" }),
  }

Depending on the value of isArriving:

// isArriving === true
{ one: 1, hello: "world" }

or

// isArriving === false
{ one: 1 }

This is useful for dynamically building up some configuration object or data payload.