Created
December 7, 2020 17:17
-
-
Save feeedback/534d85b597e3d2af852e11c81e90d28c to your computer and use it in GitHub Desktop.
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 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