tazmin32w
tazmin32w

Reputation: 157

How to add to an object keys and values of a Map as properties?

I have this object

const obj = {a: 1}

and this map

const map1 = new Map();

map1.set('b', 2);
map1.set('c', 3);

How can I add keys and values from map1 as obj params/values?

obj = {a: 1, b:2, c:3}

EDIT: just edited the object 'obj'

Upvotes: 0

Views: 40

Answers (4)

Behemoth
Behemoth

Reputation: 9310

You can use a good ol' forEach() to add values to your object.

const obj = {
  a: 1
};
const map1 = new Map();

map1.set('b', 2);
map1.set('c', 3);

map1.forEach((value, key) => {
  obj[key] = value;
});

console.log(obj);

Or use Object.fromEntries() in combination with the spread syntax.

let obj = {
  a: 1
};
const map1 = new Map();

map1.set('b', 2);
map1.set('c', 3);

obj = {
  ...obj,
  ...Object.fromEntries(map1),
};

console.log(obj);

Upvotes: 2

Tareq Alsayed
Tareq Alsayed

Reputation: 64

you could use Object.fromEntries method to do such a thing

const obj = Object.fromEntries(map);

Upvotes: 0

Brother58697
Brother58697

Reputation: 3168

Use Object.fromEntries()

const map1 = new Map();

map1.set('a', 1);
map1.set('b', 2);

const obj = Object.fromEntries(map1)
console.log(obj)

Upvotes: 1

Ola Galal
Ola Galal

Reputation: 175

const obj = Object.fromEntries(map1);

you can also check this link

Upvotes: 0

Related Questions