美文网首页
JavaScriptES6中Map与对象、数组,JSON之间的相

JavaScriptES6中Map与对象、数组,JSON之间的相

作者: nzjcnjzx | 来源:发表于2020-06-30 10:13 被阅读0次
    Map转为数组
    const map = new Map();
    map.set(1,"foo").set(2,"bar").set(3,"baz");
    const arr = [...map];
    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))
    

    相关文章

      网友评论

          本文标题:JavaScriptES6中Map与对象、数组,JSON之间的相

          本文链接:https://www.haomeiwen.com/subject/foptqktx.html