-1

Assume the following array:

var arr = [0,0,{x:0,y:0}];
var newA = arr.slice(0); 
arr[2].x =2; 
arr[2].y =2;
console.log(newA)

x and y are coordinates that are supposed to be changed. How can I store them before a function is invoked and they change (perhaps pushing to a new array)? A shallow copy with slice won't work as the copied array will update the values dynamically.

Durga
  • 15,263
  • 2
  • 28
  • 52
KT-mongo
  • 2,044
  • 4
  • 18
  • 28
  • 1
    Make a JSON string and reparse. – Teemu Apr 26 '18 at 12:21
  • 1
    Question is not very clear. Give an example of what problem you are facing through code. – Abhay Srivastav Apr 26 '18 at 12:21
  • 2
    [Please, do more research](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) then **post what you've tried** with a **clear explanation of what isn't** working and provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). Read [How to Ask a good question](https://stackoverflow.com/help/how-to-ask). Be sure to [take the tour](https://stackoverflow.com/tour) and read [this](https://meta.stackoverflow.com/questions/347937/im-new-to-stack-overflow-what-are-some-things-i-should-do-and-what-things-wil). – adprocas Apr 26 '18 at 12:21
  • Possible duplicate of [How to watch for array changes?](https://stackoverflow.com/questions/5100376/how-to-watch-for-array-changes) – vahdet Apr 26 '18 at 12:22
  • I don't know have this couldn't have been more clear. So assume the following: var arr = [0,0,{x:0,y:0}]; var newA = arr.slice(0); arr[2].x =2; arr[2].y =2; Now both arr and newA have the object coordinates x and y updated. I would like to store the newA x and y coordinates after the initial array i.e. arr has been changed – KT-mongo Apr 26 '18 at 12:27
  • Possible duplicate of [Copying array by value in JavaScript](https://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript) – adprocas Apr 26 '18 at 12:39

1 Answers1

0

You can use Object.assign to duplicate the object without creating a reference.

For example:

var arr = [0,0,{x:0,y:0}];
var bak = Object.assign({}, arr[2])

In this case, bak is not a reference to arr[2], so changing either would not affect the other.

Boaz
  • 19,892
  • 8
  • 62
  • 70