Skip to content

Commit 1e0763a

Browse files
fix: handle nested Maps in mapToObj helper (#732)
* fix: handle nested Maps in mapToObj helper * fix: mapToObj remove redundant loop
1 parent 355c60e commit 1e0763a

File tree

1 file changed

+27
-7
lines changed

1 file changed

+27
-7
lines changed

helios-ts/lib.ts

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -478,14 +478,34 @@ type Request = {
478478
params: any[];
479479
};
480480

481-
function mapToObj(map: Map<any, any> | undefined): Object | undefined {
481+
/**
482+
* Converts a Map to an object, including nested Maps and arrays of Maps.
483+
* IMPORTANT: This function will mutate input!
484+
*
485+
* @param map - The Map to convert
486+
* @returns The converted object
487+
*/
488+
function mapToObj(map: Map<any, any> | undefined): Record<string, any> | undefined {
482489
if (!map) return undefined;
483490

484-
return Array.from(map).reduce((obj: any, [key, value]) => {
485-
if (value !== undefined) {
486-
obj[key] = value;
487-
}
491+
const result: Record<string, any> = {};
492+
493+
for (const [key, value] of map) {
494+
if (value === undefined) continue;
488495

489-
return obj;
490-
}, {});
496+
if (value instanceof Map) {
497+
result[key] = mapToObj(value);
498+
} else if (Array.isArray(value)) {
499+
for (let i = 0; i < value.length; i++) {
500+
if (value[i] instanceof Map) {
501+
// Mutate in-place
502+
value[i] = mapToObj(value[i]);
503+
}
504+
}
505+
result[key] = value;
506+
} else {
507+
result[key] = value;
508+
}
509+
}
510+
return result;
491511
}

0 commit comments

Comments
 (0)