conditionally spread in javascript

To conditionally spread an object or an array in JavaScript, we first need to understand the spread operator. The spread operator allows an iterable (e.g. an array) to be expanded into individual elements.

Here's an example of using the spread operator to concatenate two arrays:

index.tsx
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const concatenatedArray = [...array1, ...array2]; // [1, 2, 3, 4, 5, 6]
124 chars
4 lines

To conditionally spread an object or array, we can use a conditional statement along with object destructuring. For instance, suppose we have an object userInfo with properties name, email, phone. We want to spread userInfo into another object contactInfo only if userInfo.phone is truthy. Here's how we could do that:

index.tsx
const userInfo = {
  name: "John Doe",
  email: "john.doe@example.com",
  phone: "+1-555-1234"
};

const shouldSpread = userInfo.phone;

const contactInfo = {
  ...userInfo,
  ...(shouldSpread && { phone: userInfo.phone })
};

console.log(contactInfo);
// Output: { 
//   name: "John Doe", 
//   email: "john.doe@example.com",
//   phone: "+1-555-1234"
// }
358 chars
20 lines

In the above example, we first create a variable shouldSpread with the value userInfo.phone. Next, we use object destructuring to spread userInfo into contactInfo. Finally, we use a conditional statement along with the spread operator to add the phone property to contactInfo only if shouldSpread is truthy.

Similarly, we could conditionally spread an array by using array spread (...) inside a conditional statement.

gistlibby LogSnag