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.
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.
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.