Skip to content

Instantly share code, notes, and snippets.

@connebs
Last active June 1, 2020 16:36
Show Gist options
  • Select an option

  • Save connebs/55a3f84c9eadcf34b02bdb05570db5ff to your computer and use it in GitHub Desktop.

Select an option

Save connebs/55a3f84c9eadcf34b02bdb05570db5ff to your computer and use it in GitHub Desktop.
Flatten a nested object into a flat object keyed by path strings
const flatten = (obj, flattened, prevStringKey) => {
Object.entries(obj).forEach(([key, value]) => {
const stringKey = prevStringKey ? `${prevStringKey}.${key}` : key;
if (typeof value === 'object') {
flattened = flatten(value, flattened, stringKey);
} else {
flattened[stringKey] = value;
}
});
return flattened;
};
const path = { in: { big: { object: true, another: false } }, out: { final: { countdown: 100 } } };
console.log(flatten(path, {}, 'path'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment