Skip to content

Instantly share code, notes, and snippets.

@panda01
Created February 2, 2015 12:36
Show Gist options
  • Save panda01/37110f26728d165ecd10 to your computer and use it in GitHub Desktop.
Save panda01/37110f26728d165ecd10 to your computer and use it in GitHub Desktop.
Simple flatten
(function() {
function flatten(obj, prevObj, path) {
var newPath = null,
makeNewPath = function(p, j) {
return p ? (p + '.' + j) : j;
};
// stop undefined from being printed
path = path || '';
prevObj = prevObj || {};
// for every obj in the target
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
newPath = makeNewPath(path, i);
if(typeof obj[i] === 'object') {
flatten(obj[i], prevObj, newPath);
} else {
prevObj[newPath] = obj[i];
}
}
}
return prevObj;
}
var obj = {
a : 1,
b: {
c: true,
d: {
e: 'something'
},
f: false
}
};
console.log(flatten(obj));
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment