Reputation: 157
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
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
Reputation: 64
you could use Object.fromEntries method to do such a thing
const obj = Object.fromEntries(map);
Upvotes: 0
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