Last active
July 19, 2019 11:09
-
-
Save alexneamtu/c4eb28b1ed44fbbb065999d64b088875 to your computer and use it in GitHub Desktop.
Flatten Object
This file contains 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
/** | |
* Takes a deeply nested object, `source`, and returns an object with | |
* dot-separated paths pointing to all primitive values from `source`. | |
* | |
* Examples: | |
* | |
* flatten({ foo: { bar: 1 } }) | |
* //=> { 'foo.bar': 1 } | |
* | |
* flatten({ foo: [{ bar: 1 }, { bar: 2 }] }) | |
* //=> { 'foo.0.bar': 1, 'foo.1.bar': 2 } | |
*/ | |
function flatten(obj, parent, res = {}){ | |
for(let key in obj){ | |
let propName = parent ? parent + '.' + key : key; | |
if(typeof obj[key] === 'object' && obj[key] === null){ | |
flatten(obj[key], propName, res); | |
} else { | |
res[propName] = obj[key]; | |
} | |
} | |
return res; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment