Resting and spreading can be used for more than just resting arguments and spreading arrays.
Clone an object while simultaneously adding additional properties to the cloned object.
In this example
user is cloned and
password is added into
Merge two objects into a new object.
part2 are merged together into
Objects also be merged with this syntax:
Properties can be removed using destructuring in combination with the rest operator. Here
password is destructured out (ignored) and the
rest of the properties are returned as
removeProperty function takes a
prop as an argument. Using computed object property names the
prop can be excluded dynamically from the clone.
Sometimes properties aren’t in the order we need them to be. Using a couple of tricks we can push properties to the top of the list or move them to the bottom.
id to the first position, add
id: undefined to the new Object before spreading
password to the last property, first destructe
password out of
object. Then set
password after spreading
Default properties are values that will be set only when they are not included in the original object.
In this example,
user2 does not contain
setDefaults function ensures all objects have
quotes set otherwise it will be set to
setDefaults(user2), the return value will include
user4 already has
quotes, that property will not be modified.
It can also be written like this if you want the defaults to appear first instead of last:
By combining the techniques above, a function can be created to rename properties.
Imagine there are some objects with an uppercase
ID that should be lowercase. Start by destructuring
ID out of the
object. Then add it back as
object is being spread.
I tried to list out a handful lesser known spread and rest tricks, if you know any that I haven’t listed here, please let everyone know in the comments! If you learned something new, please share on Twitter and with your friends, it really helps!
Follow me here or on Twitter @joelnet!
Tip: Use Bit to easily discover and share components between apps. Build multiple projects faster with shared code and share your components. Try it.