Skip to content

Instantly share code, notes, and snippets.

@eswak
Last active March 4, 2016 09:46
Show Gist options
  • Save eswak/a8803fbcfb83cc52460c to your computer and use it in GitHub Desktop.
Save eswak/a8803fbcfb83cc52460c to your computer and use it in GitHub Desktop.
Get a plain object (without nested keys) based on a multi-level object
/*
* Flattens an object by creating a plain object (without nested keys).
* The returned object keys are strings with dots for nested source object.
* Example :
* flattenObj({ a: 1, b: { c: 2, d: null } }) => { 'a': 1, 'b.c': 2, 'b.d': null }
*/
function flattenObj (obj, prefix, acc) {
acc = acc || {};
prefix = prefix || '';
var separator = '.';
if (typeof obj === 'object' && obj !== null) {
for (var key in obj) {
if (typeof obj[key] === 'object' && obj[key] !== null) {
flattenObj(obj[key], prefix ? prefix + separator + key : key, acc);
}
else {
acc[prefix ? prefix + separator + key : key] = obj[key];
}
}
}
return acc;
}
/*
* Returns a diff between to objects (after flattening them)
*/
function diff (oldObj, newObj) {
var flattenedOld = flattenObj(oldObj);
var flattenedNew = flattenObj(newObj);
var diff = [];
for (var key in flattenedOld) {
if (flattenedNew[key] === undefined) {
diff.push({ 'type': '-', key: key, old: flattenedOld[key], new: null });
}
else if (flattenedNew[key] !== flattenedOld[key]) {
diff.push({ 'type': '~', key: key, old: flattenedOld[key], new: flattenedNew[key] });
}
}
for (var key in flattenedNew) {
if (flattenedOld[key] === undefined) {
diff.push({ 'type': '+', key: key, old: null, new: flattenedNew[key] });
}
}
return diff;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment