Hey everyone, I've encountered an interesting problem that I managed to solve. However, my solution is not elegant at all. I'm curious to see what creative solutions others can come up with :)
The challenge involves converting the provided response:
const response = {
"device": {
"name": "Foo",
"type": "Bar",
"telemetry": [
{
"timeStamp": "2022-06-01T00:00:00.000Z",
"temperature": 100,
"pressure": 50
},
...
]
}
};
Using these selection criteria:
const fields = ['device/name', 'device/telemetry/timeStamp', 'device/telemetry/temperature']
The goal is to generate results like this:
[
{"device/name": "Foo", "device/telemetry/timeStamp": "2022-06-01T00:00:00.000Z", "device/telemetry/temperature": 100},
...,
]
If you're interested, I'd love to hear your approach! Below is my somewhat messy code - still getting the hang of TypeScript, so bear with me :D
EDIT #1 Clarification: The response format can vary, including deeper levels of nesting or additional arrays like "superTelemetry". However, the selection criteria will only work with one array, never both.
Although the structure may change, we can rely on this rule to guide our implementation. Feel free to share any insights!
function createRecord(key: string, value: any){
return new Map<string, any>([[key, value]])
}
function getNestedData (data: any, fieldPath: string, records: Map<string, any[]>=new Map<string, any[]>()) {
let dataPoints: any = [];
const paths = fieldPath.split('/')
...
}