简体   繁体   中英

Using Object.assign on an object within an object

How do I use Object.assign to update the second object in the allMsgs array?

I have:

let v = {
  allMsgs: [
    {
        a: 111,
        b: [],
    },

    {
        a: 222,
        b: [],
    }
  ]
}

I want to have a copy of v so that it is:

let v = {
  allMsgs: [
    {
        a: 111,
        b: [],
    },

    {
        a: 222,
        b: ['newItem],
    }
  ]
}

How do I use Object.assign for this?

Simply select the part which you want to update

 let v = { allMsgs: [ { a: 111, b: [], }, { a: 222, b: [], } ] }; let vCopy = { allMsgs: v.allMsgs.map(msg => Object.assign({}, msg))}; vCopy.allMsgs[1] = Object.assign(vCopy.allMsgs[1], { b: ['newItem'] }); console.log('copy', vCopy); console.log('actual', v); 

If the goal is not to mutate the original object, then you would do it like this:

 let v = { allMsgs: [ { a: 111, b: [] }, { a: 222, b: [] } ] }; let w = { allMsgs: Object.assign([...v.allMsgs], { 1: Object.assign({}, v.allMsgs[1], {b: ['newItem']} )} )}; console.log('updated =', w); console.log('original =', v); 

Note that here the first object in allMsgs is still shared between the two objects. Only the one you wanted to change is (obviously) separate.

Libraries like immutable.js have nice methods for making such updates using a concise syntax.

Without Object.assign , you could address the array directly and push the value.

 var v = { allMsgs: [{ a: 111, b: [] }, { a: 222, b: [] }] }; v.allMsgs[1].b.push('newItem'); console.log(v); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM