Last active
November 10, 2019 11:23
-
-
Save ghoussard/9110379b2050353804a890def1f0ae3a to your computer and use it in GitHub Desktop.
MongoDB JSON Document Recursive Flat
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
/** | |
* 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