I want to convert an es6 nested Map to an object.
I tried this code:
mapToObjectRec(m) {
let lo = {}
for(let[k,v] of m) {
if(v instanceof Map) {
lo[k] = this.mapToObjectRec(v)
}
else {
lo[k] = v
}
}
return lo
}
I want to do the opposite of this function:
export declare type IElementsMap = Map<string, IElements>;
deserializeElements(json: any): IElementsMaps | any {
const elementsMap = new Map<string, IElementsMap>();
if (Array.isArray(json)) {
json.forEach(outer => {
const elementMap = new Map<string, IElements>();
outer[1].forEach(inner => {
elementMap.set(inner[0], inner[1]);
});
elementsMap.set(outer[0], elementMap);
});
return elementsMap;
}
return json;
}
I want to send converted data inside payload request (Post request).
If the Map's keys are numbers, strings, or symbols, the following technique will work -
const m =
new Map
( [ [ 'a', 1 ]
, [ 'b', 2 ]
, [ 'c'
, new Map
( [ [ 'd', 3 ]
, [ 'e', 4 ]
, [ 'f'
, new Map ([[ 'g', 6 ]])
]
]
)
]
]
)
const toObject = (map = new Map) =>
Object.fromEntries
( Array.from
( map.entries()
, ([ k, v ]) =>
v instanceof Map
? [ k, toObject (v) ]
: [ k, v ]
)
)
console .log (toObject (m))
// { a: 1
// , b: 2
// , c:
// { d: 3
// , e: 4
// , f: { g: 6 }
// }
// }
Otherwise, if the Map keys are complex objects and cannot be reliably coerced into a string, you'll have to come up with another mapping that preserves the key's actual value, such as -
const m =
new Map
( [ [ 'a', 1 ]
, [ 'b', 2 ]
, [ 'c'
, new Map
( [ [ 'd', 3 ]
, [ 'e', 4 ]
, [ 'f'
, new Map ([[ 'g', 6 ]])
]
]
)
]
]
)
const toObject = (map = new Map) =>
Array.from
( map.entries()
, ([ k, v ]) =>
v instanceof Map
? { key: k, value: toObject (v) }
: { key: k, value: v }
)
console .log (toObject (m))
// [ { key: "a", value: 1 }
// , { key: "b", value: 2 }
// , { key: "c"
// , value:
// [ { key: "d", value: 3 }
// , { key: "e", value: 4 }
// , { key: "f", value: [ { key: "g", value: 6 } ] }
// ]
// }
// ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With