Created
August 23, 2018 18:41
-
-
Save damarnez/6d367f7823de69964d4afcfee8e5b44a to your computer and use it in GitHub Desktop.
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 } }]) | |
* // => { '0.foo.bar': 1} | |
* flatten({ foo: [{ bar: 1 }, { bar: 2 }] }) | |
* //=> { 'foo.0.bar': 1, 'foo.1.bar': 2 } | |
*/ | |
function flatten(source,parentKey) { | |
return Object.keys(source).reduce((newObject, key, i) => { | |
const newKey = parentKey ? `${parentKey}.${key}` : key; | |
if(source[key] && typeof source[key] === 'object'){ | |
return Object.assign({},flatten(source[key],newKey),newObject); | |
}else{ | |
return Object.assign({},{[newKey]: source[key] },newObject); | |
} | |
},{}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment