0

Please help me. How to compare this objects?

const a = {myProp: 'value1'};
const b = a;
b.myProp = 'value2';

Always return me true. But have to return false.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Nikola
  • 1
  • Are we adding? Subtracting? What exactly are you comparing? – shadow2020 May 13 '19 at 15:32
  • Welcome to Stack Overflow! Please take the [tour] (you get a badge!), have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) I also recommend Jon Skeet's [Writing the Perfect Question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/). I'm afraid it's not at all clear what you're asking here. *"Always return me true."* Nothing in the code shown returns or outputs `true`. – T.J. Crowder May 13 '19 at 15:35
  • Note that `a` and `b` both point to the **same** object in the code above, not two different objects. `=` just makes `b` equal to `a`. The value (in `a`, and also in `b`) is an *object reference* that uniquely identifies the object elsewhere in memory. When you copy an object reference (`b = a`), it's the reference, not the object, that gets copied. – T.J. Crowder May 13 '19 at 15:35
  • 'value1' not equal 'value2'. How get it? – Nikola May 13 '19 at 15:36
  • Your problem isn't with how to compare objects, it's with how to make a copy of an object. – Barmar May 13 '19 at 16:14

1 Answers1

0

If your object is serializable then you could use something like this:

const a ={
    myProp: value1
};
const b = JSON.parse(JSON.stringify(a));
b.myProp = value2;
console.log(a.myProp); //value1
console.log(b.myProp);//value2

In Javascript when you assign an object to a variable, the variable stores the object reference. So in your code both a and b stores the same object reference. Hence when you modify b, a also changes. What the above code does is, it converts the object to a string and creates a new one. Be warned this only works for JSON serializable objects and will not work if it has functions. Also this method can be a bit inefficient. But unfortunately there is not built in methods to achieve this. You could use cloning but that would just be 1 level deep which would be called shadow cloning. If you want no references from your previous object to carry forward you would need deep cloning. Just google Deep Cloning in Javascript and you will get plenty of libraries to achieve it.

A Rogue Otaku
  • 913
  • 10
  • 20