Created
February 2, 2015 12:36
-
-
Save panda01/37110f26728d165ecd10 to your computer and use it in GitHub Desktop.
Simple flatten
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
(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