4

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

RemiM
  • 137
  • 2
  • 11
  • Don't include the `id: 2` key/value pair when you call `updateFunction()`? Also, you said you can't change `updateFunction()` to take multiple arguments, but can you change the *body* of the function? – kmoser Jun 05 '22 at 14:00
  • 1
    A simple solution may be `return {...object, ...updates, id: object.id};` – Passerby Jun 05 '22 at 14:00
  • for kmoser: I have no choice about including the id: 2 key/value pair when I call my function, I can change the body as I want but sticking with spreading if it's possible for passerBy: I considered that solution but let say that for some reason you don't have access to the id key/value pair of the first object, is there a way to achieve it ? – RemiM Jun 05 '22 at 14:10
  • @RemiM You don't have to _know_ the value of `object.id`, you just reference it. If you can spread `object`, then you should have access to `object.id`; And if you don't know what the actual key name (`id`) is, then @ThanhSonNguyen 's answer won't work for you either. – Passerby Jun 05 '22 at 14:41
  • Yeah that would work fine, thanks – RemiM Jun 07 '22 at 11:20

2 Answers2

13

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,
    }
}
Son Nguyen
  • 1,472
  • 8
  • 16
-3

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?

kmoser
  • 8,780
  • 3
  • 24
  • 40