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 =
newMap
( [ [ 'a', 1 ]
, [ 'b', 2 ]
, [ 'c'
, newMap
( [ [ 'd', 3 ]
, [ 'e', 4 ]
, [ 'f'
, newMap ([[ 'g', 6 ]])
]
]
)
]
]
)
consttoObject = (map = newMap) =>
Object.fromEntries
( Array.from
( map.entries()
, ([ k, v ]) =>
v instanceofMap
? [ 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 =
newMap
( [ [ 'a', 1 ]
, [ 'b', 2 ]
, [ 'c'
, newMap
( [ [ 'd', 3 ]
, [ 'e', 4 ]
, [ 'f'
, newMap ([[ 'g', 6 ]])
]
]
)
]
]
)
consttoObject = (map = newMap) =>
Array.from
( map.entries()
, ([ k, v ]) =>
v instanceofMap
? { 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:
consttoObject = (map = newMap) => {
if (!(map instanceofMap)) return map
returnObject.fromEntries(Array.from(map.entries(), ([k, v]) => {
if (v instanceofArray) {
return [k, v.map(toObject)]
} elseif (v instanceofMap) {
return [k, toObject(v)]
} else {
return [k, v]
}
}))
}
Post a Comment for "Javascript Convert Nested Map To Object"