let myMap = new Map([[true, 7], [{foo: 3}, ['abc']]]);
[...myMap]
console.log([...myMap]);
数组转为Map的方法
new Map([[true, 7], [{foo: 3}, ['abc']]])
Map转为对象的方法
function strMapToObj(strMap) {
let obj = Object.create(null);
for (let [k,v] of strMap) {
obj[k] = v;
}
return obj;
}
let myMap = new Map().set('yes', true).set('no', false);
console.log(strMapToObj(myMap));
// { yes: true, no: false }
对象转为Map的方法
function objToStrMap(obj) {
let strMap = new Map();
for (let k of Object.keys(obj)) {
strMap.set(k, obj[k]);
}
return strMap;
}
var a = {yes: true, no: false}
console.log(objToStrMap(a))
// [ [ 'yes', true ], [ 'no', false ] ]
Map转为Json的方法
function strMapToObj(strMap) {
let obj = Object.create(null);
for (let [k,v] of strMap) {
obj[k] = v;
}
return obj;
}
function strMapToJson(strMap1) {
return JSON.stringify(strMapToObj(strMap1));
}
let myMap2 = new Map().set('yes', true).set('no', false);
console.log(strMapToJson(myMap2));
// '{"yes":true,"no":false}'
Map转为Json数组
function mapToArrayJson(map) {
return JSON.stringify([...map]);
}
let myMap = new Map().set(true, 7).set({foo: 3}, ['abc']);
mapToArrayJson(myMap)
console.log(mapToArrayJson(myMap))
// '[[true,7],[{"foo":3},["abc"]]]'
json对象转换为Map
function objToStrMap(obj) {
let strMap = new Map();
for (let k of Object.keys(obj)) {
strMap.set(k, obj[k]);
}
return strMap;
}
function jsonToStrMap(jsonStr) {
return objToStrMap(JSON.parse(jsonStr));
}
jsonToStrMap('{"yes":true,"no":false}')
console.log(jsonToStrMap('{"yes":true,"no":false}'))
// Map {'yes' => true, 'no' => false}
json数组转换为Map
function jsonToMap(jsonStr) {
return new Map(JSON.parse(jsonStr));
}
jsonToMap('[[true,7],[{"foo":3},["abc"]]]')
console.log(jsonToMap('[[true,7],[{"foo":3},["abc"]]]'))
// Map {true => 7, Object {foo: 3} => ['abc']}