-1

I have found some people saying to use JSON but that said that another function wasn't defined and I've also tried Object.assign() my issue is I have 2 identical objects however when I modify one the other changes its because they have the same index in memory is there any way to prevent this in js Thanks in advance :)

For example:

var obj1 = {
    info: 5
}
var obj2 = obj1;
obj2.info += 1;
console.log(obj1.info == obj2.info) //returns true I don't want it to
ppovoski
  • 4,553
  • 5
  • 22
  • 28
Hypr
  • 3
  • 4
  • 3
    Possible duplicate of [What is the most efficient way to deep clone an object in JavaScript?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – Nir Alfasi Dec 14 '17 at 22:18
  • It's not quite clear what you are trying to do. Could you elaborate with some code? – SindreKjr Dec 14 '17 at 22:18
  • @Basillicum he has two references to the same object while he wants to different identical objects. – Nir Alfasi Dec 14 '17 at 22:19
  • If they're identical, they're not *two* objects but just one. – Bergi Dec 14 '17 at 22:20

1 Answers1

0

If you don't want obj2 to be a reference to obj1, then you have to define it with its own keys/values, like this:

var obj1 = {
  info: 5
};
var obj2 = {
  info: 5
};

console.log(obj1 == obj2); // false - they are not the same object
obj2.info += 1;
console.log(obj1.info == obj2.info); // false

Even though the two objects look identical and start with the same key and value, they will not be treated as equal. If you have a big object with lots of keys (and nested keys) that you don't want to keep re-typing, you'll have to write a deep copy function to fully re-create the object.

skyline3000
  • 7,639
  • 2
  • 24
  • 33