// 索引为 key 值,数组元素为 value 值 const arr1 = ['name1','name2','name3'] const obj1 = {..arr1} // { '0': 'name1', '1': 'name2', '2': 'name3' } // 数组元素为 key 值,value 值为 undefined const arr2 = ['name1','name2','name3'] const obj2 = {} arr2.forEach((item)=>{ obj2[item] = undefined }) console.log(obj2)// { name1: undefined, name2: undefined, name3: undefined }

ES6 中 Map 与对象、数组,JSON 之间的相互转换

以下内容来自 原文

  • Map转为数组
  • // 保留 key、value,转换成二元数组
    const map = new Map();
    map.set(1,"foo").set(2,"bar").set(3,"baz");
    const arr = [...map]; // 法一:[ [ 1, 'foo' ], [ 2, 'bar' ], [ 3, 'baz' ] ]
    const arr = Array.from(map); // 法二:[ [ 1, 'foo' ], [ 2, 'bar' ], [ 3, 'baz' ] ]
    
  • 数组 转为 Map
  • const arr = ["foo","bar","baz"];
    // key 值是索引、value 值是元素
    const map1 = new Map(arr.map( (value,key) => [key,value]));
    // Map(3) { 0 => 'foo', 1 => 'bar', 2 => 'baz' }
    // key 值是元素,value 值是 undefined
    const map2 = new Map(arr.map((value) => [value,undefined]));
    // Map(3) { 'foo' => undefined, 'bar' => undefined, 'baz' => 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));
    复制代码
    分类:
    前端