Last active
June 12, 2019 23:02
-
-
Save jfet97/9e4b9033baf6f272d695302e78c60220 to your computer and use it in GitHub Desktop.
objects flattening
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
const obj = { a: { b: 1, c: 2, d: { e:4 , f:[1,2,3,4,5,6,7,8,9,0]} }, g:42 }; | |
const res = Object.fromEntries(flatProps(objectRecursiveEntries(obj))); | |
/* | |
{ | |
"a.b": 1, | |
"a.c": 2, | |
"a.d.e": 4, | |
"a.d.f.0": 1, | |
"a.d.f.1": 2, | |
"a.d.f.2": 3, | |
"a.d.f.3": 4, | |
"a.d.f.4": 5, | |
"a.d.f.5": 6, | |
"a.d.f.6": 7, | |
"a.d.f.7": 8, | |
"a.d.f.8": 9, | |
"a.d.f.9": 0, | |
"g": 42, | |
} | |
*/ |
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
function flatProps(arr = [], parentKey = null) { | |
const res = []; | |
for (const [key, value] of arr) { | |
if(Array.isArray(value)) { | |
res.push(...flatProps(value, key).map(([k, v]) => { | |
const keyToInsert = parentKey ? `${parentKey}.${k}` : k; | |
return [keyToInsert, v]; | |
})); | |
} else { | |
const keyToInsert = parentKey ? `${parentKey}.${key}` : key; | |
res.push([keyToInsert, value]); | |
} | |
} | |
return res; | |
} |
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
function objectRecursiveEntries(obj = {}) { | |
const res = []; | |
for(const [key, value] of Object.entries(obj)) { | |
if(value && typeof value === "object") { | |
res.push([key, recursiveEntries(value)]) | |
} else { | |
res.push([key, value]); | |
} | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment