Created
June 13, 2020 07:04
-
-
Save AnishLushte07/497de573873055e55bbfa9f11503bf52 to your computer and use it in GitHub Desktop.
Flatten javascript objects into a single-depth object
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 flattenObj(obj, preKey) { | |
const entries = Object.entries(obj); | |
return entries.reduce((acc, curr) => { | |
let [key, value] = curr; | |
return typeof value !== 'object' | |
? Object.assign(acc, { [preKey ? `${preKey}.${key}` : key] : value }) | |
: Object.assign(acc, flattenObj(value, preKey ? `${preKey}.${key}` : key)); | |
}, {}); | |
} | |
// Initial call do not pass preKey | |
// eg | |
console.log( | |
flattenObj({ | |
a: 20, | |
b: 'hello', | |
c: { | |
p: "234" | |
}, | |
p: { | |
q: { | |
r: { | |
l: 12, | |
m: 'rto' | |
} | |
} | |
} | |
}) | |
); | |
// output | |
// { a: 20, b: 'hello', 'c.p': '234', 'p.q.r.l': 12, 'p.q.r.m': 'rto' } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment