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

Sometimes, we want to flatten a JavaScript object keys and values to a single depth array.

In this article, we’ll look at how to flatten a JavaScript object keys and values to a single depth array.

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

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.