How to flatten deep nested objects recursively?
function flattenObject(objectTree) {
const flatObject = {};
if (!objectTree) {
return flatObject;
}
Object.keys(objectTree).forEach((rootKey) => {
if (Object.prototype.hasOwnProperty.call(objectTree, rootKey)) {
// flatten deep nested objects
if (typeof objectTree[rootKey] === 'object') {
const deepObject = flattenObject(objectTree[rootKey]);
Object.keys(deepObject).forEach((deepKey) => {
if (Object.prototype.hasOwnProperty.call(deepObject, deepKey)) {
flatObject[`${rootKey}.${deepKey}`] = deepObject[deepKey];
}
});
} else {
flatObject[rootKey] = objectTree[rootKey];
}
}
});
return flatObject;
}
const person = {
Name: 'Goku',
Attack: {
Special: {
Name: 'Kame Hame Ha',
Power: '4000'
},
Final: {
Name: 'Genkidama',
Power: '> 9000'
},
}
}
/*
returns:
{
Name: 'Goku',
'Attacks.Special.Name': 'Kame Hame Ha',
'Attacks.Special.Power': '4000',
'Attacks.Final.Name': 'Genkidama',
'Attacks.Final.Power': '> 9000'
}
*/
flattenObject(person)
July 27th, 2020
A function which executes itself (so called recursion) is a good way to flatten an object of any depth.
This algorithm uses two forEach()
loops: One for the root layer of the current object and one for it's properties.
At first, the outer loop will copy the property and it's values into flatObject
. If the value is an object itself, the second loop will start.
The inner loop copies the nested object into the flatObject
. The keys of the nested objects will be merged to a dot-notation key like key1.key2
.