-1

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);
})();
Chris
  • 2,953
  • 10
  • 48
  • 118

1 Answers1

3

You aren't copying the object. You are making a reference to it. They are the same object. You can make a copy with object.assign.

let strB = Object.assign({}, strA);
  • 2
    It just happens to be a deep copy in this case. `Object.assign`, in general, does _not_ create a deep copy. – Sebastian Simon Jul 08 '20 at 16:33
  • This works, however, I have an array of objects in the object, which I didn't show. When I change a property in the nested object, the original gets changed as well – Chris Jul 08 '20 at 17:32
  • 1
    found the solution – Chris Jul 08 '20 at 17:49
  • Yeah your nested array is just a ref in the copy. I shouldn't have said deep copy. It just makes a new unique object with the same stuff inside. – Anthony Kolka Jul 08 '20 at 18:36