Skip to content

Instantly share code, notes, and snippets.

@jfet97
Last active June 12, 2019 23:02
Show Gist options
  • Save jfet97/9e4b9033baf6f272d695302e78c60220 to your computer and use it in GitHub Desktop.
Save jfet97/9e4b9033baf6f272d695302e78c60220 to your computer and use it in GitHub Desktop.
objects flattening
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,
}
*/
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;
}
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