Last active
March 8, 2017 10:50
-
-
Save kritollm/c60b3ea6c62221b63a9e2c8c5df6e870 to your computer and use it in GitHub Desktop.
Compare objects before storing to firebase db. May not work for objects in arrays (not supposed to either). When jsonEqual would do, but property order is messed up.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var isArray = Array.isArray || function(arg) { | |
return Object.prototype.toString.call(arg) === '[object Array]'; | |
}; | |
function isObject(o) { | |
return ((o !== null) && (typeof o === 'object') && !isArray(o)); | |
} | |
function jsonEqual(object1, object2) { | |
return JSON.stringify(object1) == JSON.stringify(object2); | |
} | |
function equalObject(object1, object2) { | |
let keys1 = Object.keys(object1); | |
let keys2 = Object.keys(object2); | |
if (keys1.length != keys2.length) { | |
return false; | |
} | |
return !keys1.some(function(p) { | |
let v1 = object1[p]; | |
let v2 = object2[p]; | |
let is1 = isObject(v1); | |
let is2 = isObject(v2); | |
if (is1 != is2) { | |
return true; | |
} | |
if (is1) { | |
return !equalObject(v1, v2); | |
} | |
return !jsonEqual(v1, v2); | |
}); | |
} | |
var o1 = { | |
first: [1, 2, 3, 4], | |
second: "Some text", | |
anObject: { | |
testValue: "tEsT", | |
testArray: ["a", "b", "c"] | |
} | |
}; | |
var o2 = { | |
second: "Some text", | |
anObject: { | |
testArray: ["a", "b", "c"], | |
testValue: "tEsT" | |
}, | |
first: [1, 2, 3, 4] | |
}; | |
console.log(equalObject(o1, o2)); | |
o2.anObject.testArray.push("d"); | |
console.log(equalObject(o1, o2)); | |
o2.anObject.testArray.pop(); | |
console.log(equalObject(o1, o2)); | |
// Test for object and value/array; | |
o2.anObject = [1, 2, 3]; | |
console.log(equalObject(o1, o2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment