'How to use spread operator to add property to an object, not override it?
I have this function.
function foo(newdata) {
utils.method('GET', '/auth', {
response: {
data: {
settings: {
last_email_notification_shown_date: new Date(),
email_notifications: null,
}
...newdata
}
}
});
}
But every time I want to update the 'settings' property, I have to pass all of it to data:
foo(settings {
last_email_notification_shown_date: new Date(),
email_notifications: null,
SomeNewProperty: 'whatever'
})
Is there a way to update the 'settings' property in this function without the need to rewrite it whole? I just want to update the property, not to override it.
Solution 1:[1]
Is there a way to update the 'settings' property in this function without the need to rewrite it whole?
It's hard to tell from your question quite what you're really doing, but if the goal is to add newdata to the existing settings, you're just spreading it in the wrong place:
function foo(newdata) {
utils.method('GET', '/auth', {
response: {
data: {
settings: {
last_email_notification_shown_date: new Date(),
email_notifications: null,
...newdata // <============================ moved
}
}
}
});
}
then
foo({
SomeNewProperty: 'whatever'
});
If you need to call foo with an object with things outside settings and also within settings, then it gets slightly more complicated, but not a lot:
function foo(newdata) {
utils.method('GET', '/auth', {
response: {
data: {
...newdata, // <========================
settings: {
last_email_notification_shown_date: new Date(),
email_notifications: null,
...newdata.settings // <========================
},
}
}
});
}
then
foo({
settings: {
SomeNewProperty: 'whatever'
},
otherStuff: "foo"
});
That spreads newdata (including settings), but then overwrites newdata's settings in the new object with a replacement settings, in which we spread newdata.settings.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | T.J. Crowder |
