Map转为数组
const map = new Map();
map.set(1,"foo").set(2,"bar").set(3,"baz");
const arr = [...map];//转数组方法1

Array.from(map);//转数组方法2
console.log(arr);


数组 转为 Map
const arr = ["foo","bar","baz"];
const arrChangeMap = (arr) => new Map(arr.map( (value,key) => [key,value]));
console.log(arrChangeMap(arr));


Map 转为对象
const map = new Map();
map.set(1,"foo").set(2,"bar").set(3,"baz");
const mapChangeObj = (map) => {
     let obj = {};
     for(let [k,v] of map) {
         obj[k] = v;
     }
     return obj;
}
console.log(mapChangeObj(map));


对象转为 Map
const obj = {
       "1" : "foo",
       "2": "bar",
      "3" : "baz",
}
const objChangeMap = (obj) => {
      let map = new Map();
      for(let key in obj) {
           map.set(key,obj[key]);
      }
      return map;
}
console.log(objChangeMap(obj));
Map 转为 JSON
借助Map转对象

const map = new Map();
map.set(1,"foo").set(2,"bar").set(3,"baz");
const mapChangeJson = (map) => JSON.stringify(mapChangeObj(map));
console.log(mapChangeJson(map));
JSON 转为 Map
借助对象转Map

let json = '{"1":"foo","2":"bar","3":"baz"}';
const jsonChangeMap = (json) => objChangeMap(JSON.parse(json));
console.log(jsonChangeMap(json));

GitHub 加速计划 / js / json
18
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:3 个月前 )
2d42229f * Support BSON uint64 de/serialization Signed-off-by: Michael Valladolid <mikevalladolid@gmail.com> * Treat 0x11 as uint64 and not timestamp specific Signed-off-by: Michael Valladolid <mikevalladolid@gmail.com> --------- Signed-off-by: Michael Valladolid <mikevalladolid@gmail.com> 5 天前
1809b3d8 Signed-off-by: Niels Lohmann <mail@nlohmann.me> 5 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐