Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Conditionally spread entries to a JavaScript object

    Tomasz ŁakomyTomasz Łakomy
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: 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.

    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.

    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.

    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.

    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.