0

Conditionally spreading objects in JavaScript

 1 year ago
source link: https://www.amitmerchant.com/conditionally-spreading-objects-in-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Conditionally spreading objects in JavaScript

In JavaScript, if you want to populate an object with some properties from another object, you can use the spread operator (...) to do so.

For example, you can do something like this.

const obj = {
    a: 1,
    b: 2,
    c: 3
};

const newObj = {
    ...obj
};

console.log(newObj);
// { a: 1, b: 2, c: 3 }

But what if you want to conditionally spread the properties of an object? For example, you want to spread the properties of an object only if a certain condition is met.

I recently learned about a neat trick to do this in JavaScript. So, let’s see how we can do this.

Short-circuiting the spread operator

Essentially, we can short-circuit the spread operator using the && operator. So, if the condition is met, the spread operator will be executed and the properties of the object will be spread. Otherwise, it will be skipped.

Here’s an example.

const isActive = true;

const user = {
  name: "Amit",
  age: 30
};

const activeUsers = {
  ...isActive && user
};

console.log(activeUsers);
// { name: 'Amit', age: 30 }

As you can tell, in the example above, the user object will only get “spread” when the isActive is true and since logical AND (&&) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy, the value of the last operand is returned.

There’s one caveat though. The first operand must be a boolean value. So, if you want to use a variable as the first operand, you have to convert it to a boolean value using, let’s say, the Boolean() function.

And that’s how you can conditionally spread objects in JavaScript!

Previous: Converting PNG images to WebP using PHP Next: Discard Eloquent model changes in Laravel 9.x

Beep! Beep! I'm also running a YouTube channel which I hope you're going to love!
icon.svg

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK