How to Flatten JavaScript Object Keys and Values to a Single Depth Object?

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

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

Flatten JavaScript Object Keys and Values to a Single Depth Object

To flatten JavaScript object keys and values to a single depth object, we can create our own function to recursive traverse the object we’re flattening.

For instance, we write:

const obj = {
  name: "test",
  address: {
    personal: "abc",
    office: {
      building: 'random',
      street: 'some street'
    }
  }
}

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

const flattened = flattenObj(obj)
console.log(flattened)

to create the obj object that we want to flatten.

Then we add the flattenObj function that takes the obj, parent, and res objects.

Then we loop through the keys of the object with Object.keys and the for-of loop.

In the loop body, if parent is defined, then we concatenate the parent property name with the key we’re iterating through separated by a dot and assign it to propName.

Otherwise, we set propName to key.

If obj[key] is an object we call flattenObj with obj[key], propName, and res.

res has the flattened object result so far.

Otherwise, we set res[propName] to obj[key].

Once we’re done traversing, we return res.

Next, we call flattenObj with obj and assign it to flattened.

And then we see that flattened is:

{
  "name": "test",
  "address.personal": "abc",
  "address.office.building": "random",
  "address.office.street": "some street"
}

Conclusion

To flatten JavaScript object keys and values to a single depth object, we can create our own function to recursive traverse the object we’re flattening.