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()

1

4 Answers 4

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)

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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]);

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.