const arr1 = ['name1','name2','name3']
const obj1 = {..arr1}
const arr2 = ['name1','name2','name3']
const obj2 = {}
arr2.forEach((item)=>{ obj2[item] = undefined })
console.log(obj2)
ES6 中 Map 与对象、数组,JSON 之间的相互转换
以下内容来自 原文
Map转为数组
const map = new Map();
map.set(1,"foo").set(2,"bar").set(3,"baz");
const arr = [...map];
const arr = Array.from(map);
数组 转为 Map
const arr = ["foo","bar","baz"];
const map1 = new Map(arr.map( (value,key) => [key,value]));
const map2 = new Map(arr.map((value) => [value,undefined]));
Map 转为对象
const map = new Map();
map.set(1,"foo").set(2,"bar").set(3,"baz");
const mapToObj = (map) => {
let obj = {};
for(let [k,v] of map) {
obj[k] = v;
return obj;
console.log(mapToObj(map));
对象转为 Map
const obj = {
"1" : "foo",
"2": "bar",
"3" : "baz",
const objToMap = (obj) => {
let map = new Map();
for(let key in obj) {
map.set(key,obj[key]);
return map;
console.log(objToMap(obj));
Map 转为 JSON(借助 Map 转 JSON)
const map = new Map();
map.set(1,"foo").set(2,"bar").set(3,"baz");
const mapToJson = (map) => JSON.stringify(mapToObj(map));
console.log(mapToJson(map));
JSON 转为 Map(借助对象转 Map)
let json = '{"1":"foo","2":"bar","3":"baz"}';
const jsonToMap = (json) => objToMap(JSON.parse(json));
console.log(jsonToMap(json));
复制代码