0
data = {
    json: 'is life'
};

anoth = JSON.parse(JSON.stringify(data));

if (data == anoth){
    console.log("yes")
}else{
    console.log("nah")
}

console.log(data, anoth)

They are obviously equal but why doesnt it work in the code

Seyi Adekoya
  • 443
  • 5
  • 11

2 Answers2

0

Because you are comparing object references against each other. When you deserialized the original serialized JSON object, a new and different object was returned. The two have the same content, but they are different object instances. If you compare the JSON.stringify() versions you will get a match.

data = {
    json: 'is life'
};

anoth = JSON.parse(JSON.stringify(data));

if (data == anoth){
    alert("Objects are same.")
}else{
    alert("Objects are not same.")
}

if (JSON.stringify(data) == JSON.stringify(anoth)){
    alert("Content is same")
}else{
    alert("Content is not same.")
}

alert(JSON.stringify(data) + "\n" + JSON.stringify(anoth))
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

You should compare two objects for equality but in your example you only compare references Object comparison in JavaScript

Community
  • 1
  • 1
Vladimir G.
  • 885
  • 7
  • 15