JavaScript Recursive Flatten
Ran into the need to recursively flatten a JavaScript object and came up with this
function flatten(obj, prefix = '') {
return Object.keys(obj).reduce((results, z) => {
const currentPrefix = prefix.length ? prefix + '_' : '';
if (typeof obj[z] === 'object' && obj[z] !== null) {
Object.assign(results, flatten(obj[z], currentPrefix + z));
} else {
results[currentPrefix + z] = obj[z];
}
return results;
}, {});
}
Example
For example a nested object like this
{
"settings": [
{
"provider": "namecheap",
"domain": "example.com",
"host": "@",
"password": "e5322165c1d74692bfa6d807100c0310"
},
{
"functor": {
"property1": 1,
"property2": {
"line1": "abc",
"line2": "def"
}
}
}
]
}
Transforms into this
settings_0_domain: "example.com"
settings_0_host: "@"
settings_0_password: "e5322165c1d74692bfa6d807100c0310"
settings_0_provider: "namecheap"
settings_1_functor_property1: 1
settings_1_functor_property2_line1: "abc"
settings_1_functor_property2_line2: "def"