I have an object, and I copy that object into another variable and when I change either of the objects’ properties it gets reflected in the other object.
(function() {
let strA = {
name: "John",
age: "31",
city: "New York"
};
let strB = strA;
strA.name = "Ben";
console.log(strA);
console.log(strB);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Why is this and how do I stop it from happening?
** EDIT **
As I dug deeper into my code the assign works fine until I added an array of objects to it, as shown here
(function() {
let strA = {
name: "John",
age: "31",
city: "New York",
stuff: [
{color: "blue"},
{color: "yellow"},
{color: "red"}
]
};
let strB = Object.assign({}, strA);
strB.name = "Ben";
strB.stuff[0].color = "pink";
console.log(strA);
console.log(strB);
})();
This also changes the original object, I have tried this to no avail
(function() {
let strA = {
name: "John",
age: "31",
city: "New York",
stuff: [
{color: "blue"},
{color: "yellow"},
{color: "red"}
]
};
let strB = Object.assign({}, strA);
strb.stuff = Object.assign({}, strA.stuff);
strB.name = "Ben";
strB.stuff[0].color = "pink";
console.log(strA);
console.log(strB);
})();