Categories
JavaScript Answers

How to flatten a nested object with JavaScript?

Spread the love

To flatten a nested object with JavaScript, we use the Object.keys and array reduce method.

For instance, we write

const flattenObj = (obj = {}) => {
  return Object.keys(obj).reduce((acc, cur) => {
    if (typeof obj[cur] === "object") {
      acc = { ...acc, ...flattenObj(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 which is the flattened object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.