How to deep flatten object in JavaScript

Saurabh Mhatre
3 min readMay 5, 2023

--

How to deep flatten object in JavaScript

To deep flatten an object in JavaScript and return the result as an object, we need to iterate through the object’s properties, create new properties with flattened values, and merge the resulting objects using the spread operator.

Here’s an example of flattening Javascript Object:

const obj = {
a: 1,
b: [2, 3],
c: {
d: 4,
e: [5, 6],
f: {
g: 7
}
}
};
const flattened = deepFlattenToObject(obj);
console.log(flattened);
/*
Output:-
{
"a": 1,
"b_0": 2,
"b_1": 3,
"c_d": 4,
"c_e_0": 5,
"c_e_1": 6,
"c_f_g": 7
}
*/

In this example, `obj` contains a mix of values, including nested arrays and objects. Calling `deepFlattenToObject(obj)` returns a new object

`{a: 1, b_0: 2, b_1: 3, c_d: 4, c_e0: 5, c_e_1: 6, c_f_g: 7}`

containing all the properties in `obj`, with nested properties flattened and renamed using dot notation.

Here is an implementation for the flattening object in Javascript


function deepFlattenToObject(obj, prefix = '') {
return Object.keys(obj).reduce((acc, k) => {
const pre = prefix.length ? prefix + '_' : '';
if (typeof obj[k] === 'object' && obj[k] !== null) {
Object.assign(acc, deepFlattenToObject(obj[k], pre + k));
} else {
acc[pre + k] = obj[k];
}
return acc;
}, {});
}

This function takes an object obj and an optional prefix string as arguments. The prefix string is used to prefix the keys of the flattened properties. If no prefix is provided, an empty string is used.

The function uses Object.keys() to get an array of keys from the input obj object. It then calls the reduce() method on this array to accumulate the flattened properties into a new object, which is returned at the end of the function.

The reduce() method takes two arguments: a callback function and an initial value for the accumulator. In this case, the initial value is an empty object {}.

The callback function takes two arguments: an accumulator (acc) and the current key of the obj object (k). The callback function is called once for each key in the obj object.

Inside the callback function, the function checks if the current property value is an object and not null using the typeof operator and a null check. If it is an object, the function calls itself recursively with the current property value as the obj argument, and the prefix string concatenated with the current key as the prefix argument. The Object.assign() method is then used to merge the flattened properties returned from the recursive call into the accumulator object.

If the current property value is not an object, the function assigns the current property value to a new key in the accumulator object. The key name is the prefix string concatenated with the current key.

Finally, the function returns the accumulated object with all the flattened properties.

That’s it from my end for today. Have a nice day ahead 😁

--

--

Saurabh Mhatre
Saurabh Mhatre

Written by Saurabh Mhatre

Senior Frontend Developer with 9+ years industry experience. Content creator on Youtube and Medium. LinkedIn/Twitter/Instagram: @SaurabhNative

Responses (1)