⚠️ This lesson is retired and might contain outdated information.

Conditionally spread entries to a JavaScript object

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 2 years ago

In JavaScript, we often end up composing one object out of several other objects. Luckily there's a convenient spread operator which allows us to spread entries from one object to another.

Sometimes we only want to include something in the newly created object if a certain condition is met. In this lesson we are going to learn how to conditionally add entries to a JavaScript object using the spread operator.

Instructor: [00:00] We have a JavaScript object containing some user data. For instance, in this case, we have name and surname of the user. What we'd like to do is to construct the user object, which we want to contain the user ID, and also spread all of the user data provided in this object.

[00:16] We are displaying this object to the console over here. We have a to-do, so what we'd like to do is to check whether the user is an admin. We have a handy function for that over here. When the user is an admin, we want to set that isAdmin flag to true. Otherwise, if the user is not an admin, we don't want to add anything to the object.

[00:38] One way we could do that is to basically do, if user is an admin -- so if an admin equals true -- we could add a new property to this user object, setting isAdmin equal true. Another way would be to conditionally spread the isAdmin property to this user object.

[00:56] To do that, instead of using this if statement, do ...isAdmin. If it's true, we are going to spread the object containing isAdmin equal true. Otherwise, we are going to spread an empty object. Basically, spreading an empty object is not going to add anything to this user object, but if the user is an admin, we are going to spread this initial object containing isAdmin equals true.

[01:24] Now, we can see the result in the console over here. I have this object, which contains the isAdmin equal true. If I change it to false over here so the user is no longer an admin, what we can see here in the console, that the user is not an admin.

Wojciech Morkowski
Wojciech Morkowski
~ 5 years ago

What about: {...(isAdmin() && { is_admin: true })} ? ;)

Markdown supported.
Become a member to join the discussionEnroll Today