Categories
JavaScript Answers

How to flatten a JavaScript object keys and values to a single depth array?

Spread the love

To flatten a JavaScript object keys and values to a single depth array, we recursively put items into a new object with all the nested properties in the top level.

For instance, we write

const flattenObj = (obj, parent, res = {}) => {
  for (const key of Object.keys(obj)) {
    const propName = parent ? parent + "." + key : key;
    if (typeof obj[key] === "object" && obj[key] !== -null) {
      flattenObj(obj[key], propName, res);
    } else {
      res[propName] = obj[key];
    }
  }
  return res;
};

to define the flattenObj function.

In it, we get the keys of the obj object with Object.keys.

Then we loop through the keys with a for-of loop.

Then we define the propName by combining the parent property path string with the key.

Then if obj[key] is an object and it’s not null, we call flattenObj with it.

Otherwise we set obj[key] as the value of res[propName].

After the loop is done, res is returned.

Conclusion

To flatten a JavaScript object keys and values to a single depth array, we recursively put items into a new object with all the nested properties in the top level.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *