Created
December 16, 2021 16:38
-
-
Save gillchristian/fb577029ef8cb638e5b81705ee4ac3e1 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 isPrimitive = (x) => { | |
const t = typeof x; | |
return ( | |
t === 'string' || | |
t === 'number' || | |
t === 'boolean' || | |
t === 'undefined' || | |
t === null | |
); | |
}; | |
const buildPath = (path, key, value) => { | |
const newPath = [...path, key]; | |
return isPrimitive(value) | |
? { [newPath.join('.')]: value } | |
: Object.entries(value).reduce( | |
(acc, [k, v]) => Object.assign(acc, buildPath(newPath, k, v)), | |
{} | |
); | |
}; | |
const flatten = (obj) => | |
Object.entries(obj).reduce( | |
(acc, [key, value]) => Object.assign(acc, buildPath([], key, value)), | |
{} | |
); | |
console.log(flatten({ foo: { bar: 1 } })); | |
//=> { 'foo.bar': 1 } | |
console.log(flatten({ foo: { bar: 1, baz: 2 } })); | |
//=> { 'foo.bar': 1, 'foo.baz': 2 } | |
console.log(flatten({ foo: { bar: 1, baz: ['a', 'b'] } })); | |
//=> { 'foo.bar': 1, 'foo.baz.0': 'a', 'foo.baz.1': 'b' } | |
console.log(flatten({ a: [{ foo: 1 }, { bar: 2 }] })); | |
//=> { 'a.0.foo': 1, 'a.1.bar': 2 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment