Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude one key/value pair from spread operator return [duplicate]

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

like image 774
RemiM Avatar asked Nov 27 '25 12:11

RemiM


1 Answers

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,
    }
}
like image 127
Son Nguyen Avatar answered Nov 29 '25 01:11

Son Nguyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!