1

I'm using an Array as a container for some basic boilerplate objects which can be copied and added to another Array and then modified. The problem is when I assign the new array ownership of the object any changes persist down to the original object (which shouldn't change).

An example:

var originals = [{ name: "One", value: 1 }, { name: "Two", value: 2 }, { name: "Three", value: 3 }];

var notOriginal = [];

notOriginal.push(originals[0]);

// THIS GIVES ME - notOriginal = [{ name: "One", value: 1 }];

notOriginal[0].name = "Uno";

// THIS RESULTS IN - originals = [{ name: "Uno", value: 1 },...];

I'm trying to keep the "originals" variable the same - it shouldn't change.

I've googled quite a bit and tried some things but not sure where to find a solution.

Specifically this is happening in VueJS whereas the object is in my data()

Jon Walker
  • 143
  • 1
  • 7
  • 1
    Possible duplicate of [JavaScript - copy array of objects and make changes without modifying original array](https://stackoverflow.com/questions/45512723/javascript-copy-array-of-objects-and-make-changes-without-modifying-original-a) – yuriy636 Jan 25 '18 at 18:09

4 Answers4

3

Make a deep copy of it using JSON.parse & JSON.stringify

var originals = [{
  name: "One",
  value: 1
}, {
  name: "Two",
  value: 2
}, {
  name: "Three",
  value: 3
}];

var notOriginal = [];

notOriginal.push(JSON.parse(JSON.stringify(originals[0])));



notOriginal[0].name = "Uno";
console.log(originals)
brk
  • 48,835
  • 10
  • 56
  • 78
1

You can use Object.assign to make a copy of the object.

var originals = [{
  name: "One",
  value: 1
}, {
  name: "Two",
  value: 2
}, {
  name: "Three",
  value: 3
}];

var notOriginal = [];

notOriginal.push(Object.assign({}, originals[0]));

notOriginal[0].name = "Uno";

console.log(originals);
Chris Riebschlager
  • 1,323
  • 1
  • 8
  • 12
1
Objects are passed by reference.

In order to copy an object you can use Object.assign({}, obj) which will return a new object with the duplicated properties within obj.

var originals = [{ name: "One", value: 1 }, { name: "Two", value: 2 }, { name: "Three", value: 3 }];

var notOriginal = originals.map(obj => Object.assign({}, obj));

notOriginal[0].name = "bart";
console.log(originals[0], notOriginal[0]);
zfrisch
  • 8,474
  • 1
  • 22
  • 34
0

I found a solution by using jQuery.extend(true, {}, myObj); but would still like to know what this is called so I can understand this reactivity better.

Thanks

Jon Walker
  • 143
  • 1
  • 7