Here’s a shorter, readable way to copy props from one object to another subject to defined conditions.
The shortest way to copy object (when you don’t quite care about copying sub objects by reference) -
But, what do you do if you want to copy only
name but not
A common way to do that will be -
Not bad - the code is readable and we have accomplished the task in two lines.
But, why stop there - there is always an easier way.
And, that easy way in this case happens to be using the spread operator. We will just build on the spread operator example provided at the beginning of this post to do conditional copying of object’s props.
In hindsight, this is no magic at all. We just used the familiar spread syntax to assign props from an object.
- We included
positionas the first prop so that the variable gets
- while the rest of
I still prefer the
.forEach in my code - that makes the tasks more explicit and keep everyone else in the team happy.