只是想知道是否有人知道用嵌套路徑宣告物件的好方法,該路徑也使用擴展語法。
這是一個我知道有效的例子:
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'
但是我想做這樣的事情,我使用擴展語法復制整個物件,并在同一個宣告中覆寫/創建一個路徑并設定它的值。
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'
}
謝謝!
uj5u.com熱心網友回復:
const copyMe = {
name: 'mike',
id: '123abc456def',
nested: {
path: 'the old value'
}
}
const newObject = {
...copyMe,
nested: { ...copyMe.nested }
}
或者
const copyMe = {
name: 'mike',
id: '123abc456def',
nested: {
path: 'the old value'
}
}
const newObject = {
...copyMe,
nested: {
path: 'new value here'
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/504497.html
標籤:javascript 目的 扩展语法
上一篇:我正在嘗試在顫動的串列中的物件內創建一個串列,幫助我
下一篇:編輯每個物件陣列的鍵和值
