Trying to dynamically retrieve the keys of a nested object is proving to be quite challenging. Take for instance this sample object:
{
ts: "2021-05-06T11:06:18Z",
pr: 94665,
pm25: 5,
co2: 1605,
hm: 32,
m: {
isConnected: true,
wifidBm: 0,
},
pm1: 5,
s: {
"0": {
runningTime: 0,
sn: "05064906137109790000",
wearRate: 0,
enabled: true,
co2: 1605,
},
"1": {
enabled: false,
sn: "125630092251006",
},
"2": {
enabled: false,
sn: "05064906137109450000",
},
"3": {
fanStatus: 0,
pm25: 5,
pm1: "5",
e: {
rawSensorError: 0,
},
pm10: 5,
runningTime: 0,
sn: "125630100924141",
wearRate: 0,
enabled: true,
},
},
id: "avo_jggv6bsf211",
tp: "20.6",
pm10: 5,
type: "monitor",
}
An example of the desired output would be:
str = 'ts, pr, pm25, co2, hm, "m.isConnected, m. wifiBm, pm1, s.0.runningTime, s.0.sn, ...'
The current code snippet in use:
guessHeader(object: MeasurementModel | any, parentKey?: string): string[] {
// Looping on object's keys
Object.keys(object).forEach(key => {
if (typeof object[key] === 'object' && key !== 'ts') {
// If the object is an array recurse in it
return this.guessHeader(object[key], key)
} else {
// If we have a parentKey keep header as
if (parentKey)
this.header.push(`${parentKey}.${key}`)
else
this.header.push(key)
}
})
return this.header
}
While it works for the key "m," providing "m.isConnected" and "m.wifiBm," there are issues with keys like "s.0.runningTime," where only "0.runningTime" is returned. Given that the object structure may change and become even more complex, it is crucial to find a solution that accommodates all scenarios. Attempts to save the keys in an array for later parsing have thus far been unsuccessful.