Sometimes, we want to flatten a nested object with JavaScript.
In this article, we’ll look at how to flatten a nested object with JavaScript.
How to flatten a nested object with JavaScript?
To flatten a nested object with JavaScript, we use the Object.keys and array reduce method.
For instance, we write
const crushObj = (obj = {}) => {
return Object.keys(obj).reduce((acc, cur) => {
if (typeof obj[cur] === "object") {
acc = { ...acc, ...crushObj(obj[cur]) };
} else {
acc[cur] = obj[cur];
}
return acc;
}, {});
};
to call Object.keys with obj to get an array of keys.
Then we call reduce with a callback to recursively call crushObj when obj[cur] is an object.
And we put the properties in the acc object.
Otherwise, we put obj[cur] in acc.
We then return acc.
Conclusion
To flatten a nested object with JavaScript, we use the Object.keys and array reduce method.