0

I have an array of objects which I want to make a copy of so I can modify later and not affect the original.

const myArray = [
    {
      id: 111,
      name: 'Nikki',
    },
    {
      id: 222,
      name: 'Jimbo',
    },
    {
      id: 333,
      name: 'Frank',
    },
];

To make the copy Ive used this below which works but I still feels a bit hacky

const copyOfMyArray = JSON.parse(JSON.stringify(myArray));

I have seen Object.assign({}, obj) being suggested for this but when I try to use it as below and transform it later myArray is still affected.

const copyOfMyArray = Object.assign([{}], myArray)

Is there any way to use Object.assign so it removes the original object reference?

UXCODA
  • 908
  • 12
  • 29

0 Answers0