I don't know the scope, but using prototype inheritance and hasOwnProperty , it is almost trivial to collapse your own.
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
var objectToTrack = getFromServer();
var objectToModify = object(objectToTrack);
edit(objectToModify);
var changes = {};
for(var p in objectToModify) {
if(objectToModify.hasOwnProperty(p)) {
changes[p] = objectToModify[p];
}
}
sendChanges(changes);
One caveat: prototype inheritance (due to lack of a better word) is "shallow." If the object has any properties of the array or object, then changing them will change the original, which may not be what you want. They will also not be found hasOwnProperty. To fix this, your editing logic should be aware of when the user properties of a sub-object or array are edited by the user and tracked individually, using the same technique. eg.
var foo = { foo: [1,2,3], bar: 0, baz: { hello: "world!" } };
var bar = object(foo);
bar.foo[1] = 3;
bar.bar = 123;
function editFooArray(index,value) {
if(!bar.hasOwnProperty('foo')) {
bar.foo = bar.foo.slice(0);
}
bar.foo[index] = value;
}
function editBazObj(property,value) {
if(!bar.hasOwnProperty('baz')) {
bar.baz = object(foo.baz);
}
bar.baz[property] = value;
}
source
share