2

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?

4 Answers 4

3

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}) 
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

That's a good point to make about the Map keys. A Map could have keys 1 and "1" but the final object will only support string keys
1

There is not a builtin method but you can do something like

let map = new Map([ ['foo', 1] ]); let obj = { bar: 2 }; const merge = (map, obj2) => { return Object.assign({}, obj2, ...Array.from(map).map(([k, v]) => ({[k]: v}))); } console.log(merge(map, obj));

Comments

0

Iterate 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 }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.