how to convert Map to Object in js
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(`\nobj`, 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(`\nobj`, obj);
// obj { a: 1, b: 2, c: 3 }
js Object to Map
js 构造函数 初始化 Map
// 二维数组
const modalMap = new Map([
['image', 'img'],
['video', 'video'],
]);
// entries
const modalMap = new Map({
image: 'img',
video: 'video',
});
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/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13757389.html
未经授权禁止转载,违者必究!

浙公网安备 33010602011771号