Skip to content

Instantly share code, notes, and snippets.

@feeedback
Created December 7, 2020 17:17
Show Gist options
  • Save feeedback/534d85b597e3d2af852e11c81e90d28c to your computer and use it in GitHub Desktop.
Save feeedback/534d85b597e3d2af852e11c81e90d28c to your computer and use it in GitHub Desktop.
const input = {
a: '1',
b: {
c: '2',
d: '3',
e: {
f: '4',
g: {},
},
},
};
const flatDeepObject1 = (obj) =>
Object.entries(obj).reduce(
(acc, [key, val]) => (Object(val) === val ? { ...acc, ...flatDeepObject1(val) } : { ...acc, [key]: val }),
{}
);
const flatDeepObject2 = (obj) =>
Object.entries(obj).reduce(
(acc, [key, val]) => ({ ...acc, ...(Object(val) === val ? flatDeepObject2(val) : { [key]: val }) }),
{}
);
const getEntries = (obj) =>
Object.entries(obj).flatMap(([key, val]) => (Object(val) === val ? getEntries(val) : [[key, val]]));
const flatDeepObject3 = (obj) => Object.fromEntries(getEntries(obj));
console.log(flatDeepObject1(input));
console.log(flatDeepObject2(input));
console.log(flatDeepObject3(input));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment