javascriptspread-syntaxecmascript-2018

Spread syntax for complex objects


Assume I have an object like this

let store = {
  "articles": [{...}, {...}, ...],
  "errors": { "p1": { "myNewObject":0 }, "p2": {...}, ...}
}

I want to take advantage of Spread syntax to return a clone of this object where store.errors.p1 is a new object. Is the following the simplest way?

let newStore = { ...store, ...{ errors: { ...store.errors, p1: { "myNewObject":1 } } } }

Solution

  • No it is not the simplest syntax to clone your store and do a deep copy of p1, but it's very close:

    let newStore = { ...store, ...{ errors: { ...store.errors, p1: { myNewObject: 1 } } } }
    //                         ^^^^                                                     ^
    //                           |_______ not necessary ________________________________|
    

    You can remove the extra spread and brackets around errors.

    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))