I need to merge a Map instance w/ an object. This didn't work:
> map = new Map([ ['foo', 1] ]) Map { 'foo' => 1 } > Object.assign({}, map) {} Looks like Object.assign doesn't like maps.
Is there a nice, es6 way for converting maps to objects?
I need to merge a Map instance w/ an object. This didn't work:
> map = new Map([ ['foo', 1] ]) Map { 'foo' => 1 } > Object.assign({}, map) {} Looks like Object.assign doesn't like maps.
Is there a nice, es6 way for converting maps to objects?
You can convert it to an array via Array.from or the spread operator, then reduce that to an object, using the existing object as the initial value.
This will prefer the Map keys over any existing object keys.
const map = new Map([ ['foo', 1] ]) const mergeSource = {foo: 3, bar: 4} const obj = [...map].reduce((o, [k,v]) => ({...o, [k]: v}), mergeSource) console.info(obj) If the existing object keys should take priority, reverse the reduce callback expression
(o, [k,v]) => ({[k]: v, ...o}) Surprisingly, I couldn't find a cleaner way than iterating through the entries and building up an object:
const map = new Map([ ['foo', 1], ['bar', 2] ]); const output = {}; for (const [key, value] of map) { output[key] = value; } console.log(output); Caveat: This will overwrite any keys with the same string value, with the latter one winning.
Map keys. A Map could have keys 1 and "1" but the final object will only support string keysIterate through entries and add them to your object. This assumes keys as string. If not, they would be automatically converted to string
const to_obj = ( map => { const obj = {}; map.forEach ((v,k) => { obj[k] = v }); return obj; }); // -------------------------------------------------- // test const m = new Map([["a", 1], ["b", 2], ["c", 3]]); console.log ( to_obj (m) ); // { a: 1, b: 2, c: 3 }