javascript-传播复杂对象的语法
作者:互联网
假设我有一个这样的对象
let store = {
"articles": [{...}, {...}, ...],
"errors": { "p1": { "myNewObject":0 }, "p2": {...}, ...}
}
我想利用Spread syntax返回此对象的副本,其中store.errors.p1是新对象.以下是最简单的方法吗?
let newStore = { ...store, ...{ errors: { ...store.errors, p1: { "myNewObject":1 } } } }
解决方法:
不,克隆存储并复制p1的深层副本不是最简单的语法,但是它非常接近:
let newStore = { ...store, ...{ errors: { ...store.errors, p1: { myNewObject: 1 } } } }
// ^^^^ ^
// |_______ not necessary ________________________________|
您可以删除多余的点差和错误周围的括号.
const store = { articles: [{ a: 1 }], errors: { p1: { myNewObject: 0 }, p2: { a: 1 } } }
const newStore = { ...store, errors: { ...store.errors, p1: { myNewObject: 1 } } }
console.log(JSON.stringify(store))
console.log(JSON.stringify(newStore))
标签:spread-syntax,javascript,ecmascript-2018 来源: https://codeday.me/bug/20191024/1922731.html