Let say I have an object and a function that takes one update object and return a new object with the first one and the update one like so :
const object = {
id: 1,
value: 'initial value'
}
const updateFunction = (updates) => {
return {
...object,
...updates
}
}
const updatedObject = updateFunction({
id: 2,
value: 'updated value'
})
Using the spread operator is there a simple way to exclude the id from spreading thus updating it knowing that I absolutely can't change my updateFunction to take multiple arguments
Edit: in the comments someone suggested a simple solution like so :
return {...object, ...updates, id: object.id};
But let say that for some reason we don't have access to the id value of the first object, is there a way to just exclude the id key/value pair from the spreading ?
thank you
I wouldn't recommend deleting id of updates like kmoser's answer. This will directly change the object that is passed in, which is usually unexpected.
Instead, you can exclude id in a way that doesn't affect updates:
const updateFunction = (updates) => {
const { id, ...rest } = updates;
return {
...object,
...rest,
}
}
Delete the 'id' property from 'updates' before doing the spread:
const updateFunction = (updates) => {
delete updates['id']
return {
...object,
...updates
}
}
Reference: How do I remove a property from a JavaScript object?