Conditionally copy props to new object in Javascript

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) -

const planet = { name: "earth", position: 3 };

const newPlanet = { ...planet };
console.log(newPlanet);
// { name: 'earth', position: 3 }

But, what do you do if you want to copy only name but not position?

A common way to do that will be -

const planet = { name: "earth", position: 3 };
const newPlanet = {};
Object.keys(planet).forEach(key => {
  key == "position" ? "" : (newPlanet[key] = key);
});
console.log(newPlanet);

// { name: 'name' }

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.

const planet = { name: "earth", position: 3 };

const { position, ...newPlanet } = planet;
console.log(newPlanet);
// { name: 'earth'}

In hindsight, this is no magic at all. We just used the familiar spread syntax to assign props from an object.

  • We included position as the first prop so that the variable gets position variable/value from planet
  • while the rest of planet goes to newPlanet object

I still prefer the .forEach in my code - that makes the tasks more explicit and keep everyone else in the team happy.

comments powered by Disqus