how to convert Map to Object in js
Map to Object
just using the ES6 ways
Object.fromEntries
const log = console.log;
const map = new Map();
// undefined
map.set(`a`, 1);
// Map(1) {"a" => 1}
map.set(`b`, 2);
// Map(1) {"a" => 1, "b" => 2}
map.set(`c`, 3);
// Map(2) {"a" => 1, "b" => 2, "c" => 3}
// Object.fromEntries ✅
const obj = Object.fromEntries(map);
log(`
obj`, obj);
// obj { a: 1, b: 2, c: 3 }
...spread
& destructuring assignment
const log = console.log;
const map = new Map();
// undefined
map.set(`a`, 1);
// Map(1) {"a" => 1}
map.set(`b`, 2);
// Map(1) {"a" => 1, "b" => 2}
map.set(`c`, 3);
// Map(2) {"a" => 1, "b" => 2, "c" => 3}
const autoConvertMapToObject = (map) => {
const obj = {};
for (const item of [...map]) {
const [
key,
value
] = item;
obj[key] = value;
}
return obj;
}
const obj = autoConvertMapToObject(map)
log(`
obj`, obj);
// obj { a: 1, b: 2, c: 3 }
refs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
https://2ality.com/2015/08/es6-map-json.html
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!