-1

I search on net about how to compare the Object in javascript. All solution generally focus on JSON.stringify. JSON.stringify compare the object that has only absolute property means fixed value.

The JSON.stringify() method converts a JavaScript value to a JSON string.

There are (essentially) two built-in types in JS (null and undefined are special):

Primitive types (boolean, number, string, null*, undefined*).

Reference types - except primitive all are treated as an object like function.

Why JSON.stringify is not able to compare an object that has the function?

var a = {a:'xyz',
        fun: function () { var a = 10;}};
var b = {a:'xyz',
            fun: function () { var a = 10;}};

a == b => false
a === b => false
a.fun == b.fun => false
a.a == b.a => true

I searched on net then I found JSON.stringify for object comparison.

JSON.stringify(a) === JSON.stringify(b) => true 

but when I try with modified b

var b = {a:'xyz',
            fun: function () { var a = 15;}}; //change a from 10 to 15.

Now I check

JSON.stringify(a) === JSON.stringify(b) => true

How it possible and how to compare an object that has a function property?

eigenharsha
  • 2,051
  • 1
  • 23
  • 32

2 Answers2

1

JSON.stringify doesn't stringify function inside the object by default. Use a replacer like

 JSON.stringify(a, function(key, val) {
    return (typeof val === 'function') ? '' + val : val;
})

var a = {a:'harsha',
        fun: function () { var a = 10;}};
var b = {a:'harsha',
            fun: function () { var a = 15;}};

console.log(JSON.stringify(a, function(key, val) {
    return (typeof val === 'function') ? '' + val : val;
}),JSON.stringify(b))

console.log(JSON.stringify(a, function(key, val) {
    return (typeof val === 'function') ? '' + val : val;
}) === JSON.stringify(b, function(key, val) {
    return (typeof val === 'function') ? '' + val : val;
}));
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

Becouse JSON.stringify doesn't stringify functions. It takes only object parameters.

var a = {a:'harsha',
        fun: function () { var a = 10;}};
var b = {a:'harsha',
            fun: function () { var a = 15;}};

console.log(JSON.stringify(a));
console.log(JSON.stringify(b));
console.log(JSON.stringify(JSON.stringify(a) === JSON.stringify(b)));
Jurij Jazdanov
  • 1,248
  • 8
  • 11