Sometimes I'll need to compare to data structures (e.g. an object or array) to determine whether they have the same members and member values.
To this end, I've written Object.identical.js().
Object.identical = function (a, b, ignoreOrder) {
function sort(o) {
if (Array.isArray(o)) {
return o.sort();
}
else if (typeof o === "object") {
return Object.keys(o).sort().map(function(key) {
return sort(o[key]);
});
}
return o;
}
if (ignoreOrder === true) {
a = sort(a);
b = sort(b);
}
return JSON.stringify(a) === JSON.stringify(b);
}
Any feedback?
One specific question I have is, because the script uses ECMAScript5 Array.isArray()
and Object.keys()
, should I convert my Object.identical.js
script to not use them and instead use code that would work in previous versions of ECMAScript? I believe I would just have to change two lines of code, and add two.
Feedback wanted! Thanks!