just wondering if anyone knows of a good way to declare an object with a nested path that also is using spread syntax.
Here is an example that I know works:
const copyMe = {
name: 'mike',
id: '123abc456def',
nested: {
path: 'the old value'
}
}
const newObject = {
...copyMe,
}
// Works, but adds an extra line of code.
newObject.nested.path = 'the new value'
console.log(newObject) // newObject.nested.path = 'the new value'
However I would like to do something like this, where I copy an entire object using spread syntax, and in the same declaration overwrite/create a path & set its value.
const copyMe = {
name: 'mike',
id: '123abc456def',
nested: {
path: 'the old value'
}
}
// Syntax is incorrect. Example of what I wish to accomplish.
const newObject = {
...copyMe,
...copyMe.nested.path: 'new value here'
}
Thanks!
CodePudding user response:
const copyMe = {
name: 'mike',
id: '123abc456def',
nested: {
path: 'the old value'
}
}
const newObject = {
...copyMe,
nested: { ...copyMe.nested }
}
or
const copyMe = {
name: 'mike',
id: '123abc456def',
nested: {
path: 'the old value'
}
}
const newObject = {
...copyMe,
nested: {
path: 'new value here'
}
}