The reason I want to do this is that the JavaScript objects are created from XML elements and if the element has changed I want to be able to detect that change in the JavaScript objects. So I wrote a function which maps out the differences between the first and second object. Can you improve on this function? (mapObjectDifferences
, not the helper functions.)
<html>
<head>
<title>MAP OBJECT DIFFERENCES</title>
<script type="text/javascript">
function isArray(object) {
return Object.prototype.toString.apply(object) == "[object Array]";
}
function getType(variable) {
var type = typeof variable;
if (type == "object")
if (isArray(variable))
return "array";
return type;
}
function arrayToObject(array) {
var object = {};
for (var i = 0; i < array.length; ++i)
if (array[i] !== "undefined") object[i] = array[i];
return object;
}
function mapObjectDifferences(outerObject, innerObject) {
var _mapObjectDifferences = function (outerObject, innerObject, parentMap, parentName) {
var localMap = {};
for (var outerProp in outerObject) {
if (outerObject.hasOwnProperty(outerProp)) {
var match = false;
var outerPropValue = outerObject[outerProp];
var outerType = getType(outerPropValue);
var result;
for (var innerProp in innerObject) {
if (innerObject.hasOwnProperty(innerProp)) {
var innerPropValue = innerObject[innerProp];
var innerType = getType(innerPropValue);
if (outerProp == innerProp && outerType == innerType) {
match = true;
if (outerType == "array" || outerType == "object") {
if (outerType == "array") {
outerPropValue = arrayToObject(outerPropValue);
innerPropValue = arrayToObject(innerPropValue);
}
_mapObjectDifferences(outerPropValue, innerPropValue, localMap, outerProp);
}
break;
}
}
}
if (match == false) {
localMap[outerProp] = outerType;
if (parentMap)
parentMap[parentName] = localMap;
}
else if (parentMap) {
var difChild = false;
for (var prop in localMap)
if (localMap.hasOwnProperty(prop)) {
difChild = true;
break;
}
if (difChild == true)
parentMap[parentName] = localMap;
}
}
}
return localMap;
}
return _mapObjectDifferences(outerObject, innerObject);
}
var o1 = {
val: "level one",
val2: 1,
val3: 3,
m: {
s2: "this is level two",
l1: ["a", "b", "c", 1, {a:"a"}],
ao: [{ x: "1" }, { y: 1 }, { z: 1}]
},
n: {
n1: { abc: 123 }
}
};
var o2 = {
val: "level on23e",
val2: 1,
m: {
s3: "this is level two",
l1: ["a", "b", "c"],
ao: [{ x: 1 }, { y: 1 }, { z: "3"}]
},
n: {
n1: { abc: "abc" }
}
}
var result = mapObjectDifferences(o1, o2);
debugger;
</script>
</head>
<body>
</body>
</html>
extends
function...(If jQuery is an option) \$\endgroup\$