Skip to content

Instantly share code, notes, and snippets.

@alexneamtu
Last active July 19, 2019 11:09
Show Gist options
  • Save alexneamtu/c4eb28b1ed44fbbb065999d64b088875 to your computer and use it in GitHub Desktop.
Save alexneamtu/c4eb28b1ed44fbbb065999d64b088875 to your computer and use it in GitHub Desktop.
Flatten Object
/**
* 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