Skip to content

Instantly share code, notes, and snippets.

@AnishLushte07
Created June 13, 2020 07:04
Show Gist options
  • Save AnishLushte07/497de573873055e55bbfa9f11503bf52 to your computer and use it in GitHub Desktop.
Save AnishLushte07/497de573873055e55bbfa9f11503bf52 to your computer and use it in GitHub Desktop.
Flatten javascript objects into a single-depth object
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