relidon relidon - 2 months ago 5
Javascript Question

How to mutate an object without duplication?

I have this object

var originalObj = {
shop: [
{ id: 1, list: "buy milk", complete: false},
{ id: 2, list: "buy bread", complete: false}
]
}


I would like to change the first item to
complete: true


var newObj = Object.assign({}, originalObj, {
['shop']: [
{...originalObj['shop'][0]
complete: true}, ...originalObj['shop']
]
})


The problem with this is that the
newObj
ends up with three objects, where the one I am trying to edit gets duplicated.

Answer

Deep copy may have issues sometime. Object.assign() copies the property reference when the property being assigned is an object. It is better you can use the following method.

var originalObj = {
  shop: [
    { id: 1, list: "buy milk", complete: false},
    { id: 2, list: "buy bread", complete: false}
  ]
};
var newObj = JSON.parse(JSON.stringify(originalObj));
newObj.shop[0].complete = true;