如何从传播操作员退货中排除一个键/价值对
假设我有一个对象和一个函数,该函数采用一个更新对象并返回一个带有第一个对象的对象,然后更新一个对象:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不建议删除
iD
更新
喜欢Kmoser的答案。这将直接更改传递的对象,这通常是出乎意料的。相反,您可以以不影响
更新
的方式排除ID
:I wouldn't recommend deleting
id
ofupdates
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 affectupdates
:在进行差异之前,请从“更新”中删除“ ID”属性:
参考:如何从Javascript对象中删除属性?
Delete the 'id' property from 'updates' before doing the spread:
Reference: How do I remove a property from a JavaScript object?