JavaScript Convert Nested Map To Object
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) {
Solution 1:
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 } ] }
// ]
// }
// ]
Solution 2:
If a value in the map can be an array of maps you need:
const toObject = (map = new Map) => {
if (!(map instanceof Map)) return map
return Object.fromEntries(Array.from(map.entries(), ([k, v]) => {
if (v instanceof Array) {
return [k, v.map(toObject)]
} else if (v instanceof Map) {
return [k, toObject(v)]
} else {
return [k, v]
}
}))
}
Post a Comment for "JavaScript Convert Nested Map To Object"