Skip to content

Instantly share code, notes, and snippets.

@gillchristian
Created December 16, 2021 16:38
Show Gist options
  • Save gillchristian/fb577029ef8cb638e5b81705ee4ac3e1 to your computer and use it in GitHub Desktop.
Save gillchristian/fb577029ef8cb638e5b81705ee4ac3e1 to your computer and use it in GitHub Desktop.
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