如何从传播操作员退货中排除一个键/价值对

发布于 2025-02-05 04:55:16 字数 554 浏览 1 评论 0原文

假设我有一个对象和一个函数,该函数采用一个更新对象并返回一个带有第一个对象的对象,然后更新一个对象:

const object = {
    id: 1,
    value: 'initial value'
}

const updateFunction = (updates) => {
    return {
        ...object,
        ...updates
    }
}

const updatedObject = updateFunction({
    id: 2,
    value: 'updated value'
})

使用传播操作员是否有一种简单的方法来将ID排除在传播中,从而更新它知道知道我绝对无法将我的更新功能更改为进行多个参数

编辑:在有人建议的简单解决方案的评论中:

 return {...object, ...updates, id: object.id};

但是,由于某种原因,我们无法访问第一个对象的ID值,是否有一个只是将ID密钥/值对排除在扩展中?

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼泪也成诗 2025-02-12 04:55:16

我不建议删除iD 更新喜欢Kmoser的答案。这将直接更改传递的对象,这通常是出乎意料的。

相反,您可以以不影响更新的方式排除ID

const updateFunction = (updates) => {
    const { id, ...rest } = updates;
    return {
        ...object,
        ...rest,
    }
}

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,
    }
}
蛮可爱 2025-02-12 04:55:16

在进行差异之前,请从“更新”中删除“ ID”属性:

const updateFunction = (updates) => {
    delete updates['id']
    return {
        ...object,
        ...updates
    }
}

参考:如何从Javascript对象中删除属性?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文