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'
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);
Use Object.fromEntries()
const map1 = new Map(); map1.set('a', 1); map1.set('b', 2); const obj = Object.fromEntries(map1) console.log(obj)
const obj = Object.fromEntries(map1);
you can also check this link
you could use Object.fromEntries method to do such a thing
const obj = Object.fromEntries(map);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.