Skip to content

Instantly share code, notes, and snippets.

@ghoussard
Last active November 10, 2019 11:23
Show Gist options
  • Save ghoussard/9110379b2050353804a890def1f0ae3a to your computer and use it in GitHub Desktop.
Save ghoussard/9110379b2050353804a890def1f0ae3a to your computer and use it in GitHub Desktop.
MongoDB JSON Document Recursive Flat
/**
* MongoDB JSON Document Recursive Flat
* @param {Object|Array} document MongoDB JSON Document
* @param {string|undefined} prefixKey used by recursivity to prefix deeper keys with parent keys
*/
const flat = (document, prefixKey = undefined) => {
const keys = Object.keys(document)
keys.forEach(key => {
const newKey = prefixKey ? `${prefixKey}_${key}` : key
if(document[key] instanceof Array || (document[key] instanceof Object && document[key].constructor === Object)) {
document = {
...document,
...flat(document[key], newKey)
}
delete document[key]
} else if(prefixKey) {
document[newKey] = document[key]
delete document[key]
}
});
return document
}
module.exports = flat
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment