Is there a way to optimize the code below without using loops? Although I prefer not to use loops in my code, the current implementation relies on them. I'm curious if achieving the same result is possible with a different approach.
Code:
ts
private getData(): Observable<any> {
return this.httpService.get(this.urlConfig.someUrl).pipe(
map(res => {
let x = this.recurseMap(res);
})
);
}
private recurseMap(obj): Map<string, any> {
const m = new Map<string, any>();
for (let key in obj) {
if (typeof obj[key] === 'object') {
obj[key] = this.recurseMap(obj[key]);
}
m.set(key, obj[key]);
}
return m;
}
The response for
this.httpService.get(this.urlConfig.someUrl)
will be
{
"Obj1": {
"1": "A",
"2": "B",
"4": "C",
"8": "D",
"16": "E",
"32": "F",
"64": "G"
},
"Obj2": {
"0": "H",
"1": "I",
"2": "J",
"3": "K"
},
"Obj3": {
"0": "L",
"1": "M"
}
}
The resulting x
would hold values like this (map<string,map<string,string>>)
{
key: "Obj1",
value: [
{ key: "1", value: "A" },
{ key: "2", value: "B" },
{ key: "4", value: "C" },
...
]
}