-2

I just need to copy the value of data.notes. I have used below code. But still detailsOfCurrentNotes value changes according to the value of data.notes. So could you tell me how to do this?

notes :Note[]

 const detailsOfCurrentNotes = Object.assign({}, data.notes);
 //here data.notes changes
 // detailsOfCurrentNotes also get that value
Sampath
  • 63,341
  • 64
  • 307
  • 441

2 Answers2

2

If the object/array is not circular, you can simply do:

const detailsOfCurrentNotes = JSON.parse(JSON.stringify(data.notes));
Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
0

If notes is an array, it is:

const detailsOfCurrentNotes = Object.assign([], data.notes);

And shorter syntax is:

const detailsOfCurrentNotes = [...data.notes];

This creates shallow copy of an array.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • And a shallow copy is cleary not what TO is asking for: _"But still `detailsOfCurrentNotes` value changes according to the value of `data.notes`"_ – Andreas Mar 10 '18 at 13:42
  • @Andreas The question isn't clear enough about the details, so reading OP's thoughts is a bit far-fetched – Estus Flask Mar 10 '18 at 13:44