Modifying objects with spread operator
October 6, 2023
Recently I have been faced with the following problem: I want to remove some properties from the existing object using JavaScript (or TypeScript for that matter). I knew about Object.keys(obj)
syntax, but wanted to try the not-so-new spread operator. Here's what I found out.
First approach
Imagine I have the following object that I want to modify:
const obj = {
prop1: "A",
prop2: "B",
prop3: "C",
prop4: "D",
prop5: "E"
}
Now let's imagine I want to create a new object that would have only prop1
and prop5
. The rest should simply bbe ignored. This is one cool way to do it:
const {prop2, prop3, prop4, ...newObj } = obj
console.log(newObj)
// {prop1: "A", prop5: "E"}
Reverse the logic
By listing all the attributes that we do not want to keep from the original object, we leave out only the ones that are interesting to us. It could work with the small objects, with limited lenth. However, for the bigger objects (think 150 properties), using the method shown above would be tedious.
That's an example of one task where the 'traditional' approach is more useful, such as here:
const obj = {
prop1: "A",
prop2: "B",
prop3: "C",
prop4: "D",
prop5: "E"
//...
prop150: "42"
}
// Specify the properties you want to pick
const propertiesToPick = ['prop1', 'prop3', 'prop150'];
// Create a new object with only the specified properties using ES6
const newObject = propertiesToPick.reduce((obj, property) => {
obj[property] = originalObject[property];
return obj;
}, {});
console.log(newObject);
// { prop1: 'value1', prop3: 'value3', prop150: "42" }
An alternative solution can use Object.assign()
method, but I like the syntax less:
const propertiesToPick = ['prop1', 'prop3', 'prop150'];
const newObject = Object.assign({}, ...propertiesToPick.map(prop => ({ [prop]: originalObject[prop] })));
// { prop1: 'value1', prop3: 'value3', prop150: "42" }
And here we are, a few tiny little tools that can be reused in the future!