Created
October 26, 2021 12:45
-
-
Save coffee-mug/e59e251d4eaed9e953a1bf784661f0e7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// flattenObject recursively takes an object with an arbitrary depth | |
// and return an object with all properties grouped at the root level. | |
// Useful to have reduce digitalData to the same level | |
// Exemple: | |
// const nestedObject = { a: { b: 1}, c: { d: { e: 3 }}}, f: [1,2,{ g: "lol"}]} | |
// flattenObject(nestedObject, null, {}) | |
// { b: 1, e: 3, f: [1,2], g: "lol"} | |
function flattenObject(object, key, output) { | |
// It's an object ? Recrusive call | |
if (typeof object == "object" && !(object instanceof Array)) { | |
Object.keys(object).forEach(property => flattenObject(object[property], property, output)); | |
// An array ? Recursive call ! | |
} else if (object instanceof Array) { | |
object.forEach(value => flattenObject(value, key, output)); | |
// a primitive - (we don't handle Set, Map, ...) for now | |
} else { | |
if (output[key] != undefined) { | |
if (output[key] instanceof Array) { | |
output[key].push(object); | |
} else { | |
var temp = []; | |
temp.push(output[key]); | |
temp.push(object); | |
output[key] = temp; | |
} | |
} else { | |
output[key] = object; | |
} | |
return output; | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment