Skip to content

Instantly share code, notes, and snippets.

@claudiabdm
Last active August 27, 2021 13:06
Show Gist options
  • Select an option

  • Save claudiabdm/38506721dac62f5f78ccaec330af6b42 to your computer and use it in GitHub Desktop.

Select an option

Save claudiabdm/38506721dac62f5f78ccaec330af6b42 to your computer and use it in GitHub Desktop.
Flatten JavaScript object using recursion, reduce and spread operator.
function flattenObject(obj) {
return Object.keys(obj).reduce((newObj, key) => {
const isObject =
typeof obj[key] == "object" &&
obj[key] != null &&
!Array.isArray(obj[key]) &&
Object.keys(obj[key]).length > 0;
if (isObject) {
newObj = { ...newObj, ...flattenObject(obj[key]) };
} else {
newObj[key] = obj[key];
}
return newObj;
}, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment