0

In my program, I have 2 objects, A and B, with some code like this:

var a = {"color":"blue"};
var b = a;
a.color = "orange";
console.log(b.color);

By setting B to A, they point to the same memory, and I don't want them to do that. I thought of running a for loop of all the keys and values, setting them individually to B, but there's got to be a better way. Any ideas?

erikvold
  • 15,988
  • 11
  • 54
  • 98
n w
  • 23
  • 3
  • ah, it also does. i just didn't know what deep cloning was, and i only need shallow cloning – n w Jun 26 '21 at 03:48

2 Answers2

3

You can use spread syntax to clone the object.

But remember it is just a shallow copy

var a = {
  color: "blue"
};
var b = { ...a };

b.color = "red";

console.log(a);
console.log(b);
console.log(a.color);
console.log(b.color);
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • lifesaver! tysm! i'm just using json to store strings, so i don't think i'd need a deep copy – n w Jun 26 '21 at 03:18
0

There are libraries, like lodash, with clone functions, but for a simple, shallow cloning, you can use:

let b = Object.assign({}, a);
kshetline
  • 12,547
  • 4
  • 37
  • 73