JavaScript Convert a Map to a regular object

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?

Answer:1

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)
Answer: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);
Answer:3

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));
Answer:4

I have JSON array that looks like var data = { "fields": [{ "firstName": { "fieldName": "First Name", "required": true, "provided": false } }, { "...

I have JSON array that looks like var data = { "fields": [{ "firstName": { "fieldName": "First Name", "required": true, "provided": false } }, { "...

I have lodash cdn included in this fiddle https://jsfiddle.net/byhh6Lyo/ console.log(_) console.log(_.range(1, 10)) _.map([1,2,3], (o) => console.log(o)) //worked The second line has an error, ...

I have lodash cdn included in this fiddle https://jsfiddle.net/byhh6Lyo/ console.log(_) console.log(_.range(1, 10)) _.map([1,2,3], (o) => console.log(o)) //worked The second line has an error, ...

  1. lodash range function

I have this PHP array ($savedRequestDates) of dates: Array ( [0] => 2018-03-29 10:56:31 [1] => 2018-03-29 10:58:09 [2] => 2018-04-12 11:28:41 [3] => 2018-04-12 13:07:25 [4] => 2018-05-...

I have this PHP array ($savedRequestDates) of dates: Array ( [0] => 2018-03-29 10:56:31 [1] => 2018-03-29 10:58:09 [2] => 2018-04-12 11:28:41 [3] => 2018-04-12 13:07:25 [4] => 2018-05-...

In this code the function sayHi() doesn't write text with style. Why? How do I apply CSS class to a document.write in a function? .class1 { color: red; font-size: 400%; } <script ...

In this code the function sayHi() doesn't write text with style. Why? How do I apply CSS class to a document.write in a function? .class1 { color: red; font-size: 400%; } <script ...

  1. word cannot apply style
  2. cannot apply paragraph style