I'm looking to convert a nested JSON structure into a single object with dynamic keys. I attempted the code below, which only works for one level. I need help writing a recursive function to handle n levels of nesting. Any advice would be appreciated.
data.map((e) => {
for (let key in e) {
if (typeof e[key] === "object") {
for (let onLevel in e[key]) {
e[key + "." + onLevel] = e[key][onLevel];
}
}
}
});
Example
Input JSON
[{
"Id": "0hb3L00000000jkQAA",
"Name": "P-2797",
"ContactEncounterId": "0ha3L000000001qQAA",
"StartTime": "2020-06-27T11:00:00.000Z",
"EncounterDuration": 25,
"ContactEncounter": {
"Name": "Grocery Shopping 17",
"LocationId": "1313L0000004ENlQAM",
"Id": "0ha3L000000001qQAA",
"Location": {
"Name": "Waitrose",
"LocationType": "Site",
"Id": "1313L0000004ENlQAM"
}
}
}]
Output JSON
[{
"Id": "0hb3L00000000jkQAA",
"Name": "P-2797",
"ContactEncounterId": "0ha3L000000001qQAA",
"StartTime": "2020-06-27T11:00:00.000Z",
"EncounterDuration": 25,
"ContactEncounter.Name": "Grocery Shopping 17",
"ContactEncounter.LocationId": "1313L0000004ENlQAM",
"ContactEncounter.Id": "0ha3L000000001qQAA",
"ContactEncounter.Location.Name": "Waitrose",
"ContactEncounter.Location.LocationType": "Site",
"ContactEncounter.Location.Id": "1313L0000004ENlQAM"
}]