Skip to content

Instantly share code, notes, and snippets.

@damarnez
Created August 23, 2018 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damarnez/6d367f7823de69964d4afcfee8e5b44a to your computer and use it in GitHub Desktop.
Save damarnez/6d367f7823de69964d4afcfee8e5b44a to your computer and use it in GitHub Desktop.
/**
* 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