Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Convert nested Map to object

I want to convert an es6 nested Map to an object.

I tried this code:

    mapToObjectRec(m) {
      let lo = {}
      for(let[k,v] of m) {
          if(v instanceof Map) {
              lo[k] = this.mapToObjectRec(v)
          }
          else {
              lo[k] = v
          }
      }
      return lo
    }

I want to do the opposite of this function:

export declare type IElementsMap = Map<string, IElements>;


deserializeElements(json: any): IElementsMaps | any {
    const elementsMap = new Map<string, IElementsMap>();

    if (Array.isArray(json)) {
      json.forEach(outer => {
        const elementMap = new Map<string, IElements>();
        outer[1].forEach(inner => {
          elementMap.set(inner[0], inner[1]);
        });
        elementsMap.set(outer[0], elementMap);
      });

      return elementsMap;
    }

    return json;
  }

I want to send converted data inside payload request (Post request).

like image 210
Selmi Med Avatar asked May 13 '26 18:05

Selmi Med


1 Answers

If the Map's keys are numbers, strings, or symbols, the following technique will work -

const m =
  new Map
    ( [ [ 'a', 1 ]
      , [ 'b', 2 ]
      , [ 'c'
        , new Map
            ( [ [ 'd', 3 ]
              , [ 'e', 4 ]
              , [ 'f'
                , new Map ([[ 'g', 6 ]])
                ]
              ]
            )
        ]
      ]
    )
    
const toObject = (map = new Map) =>
  Object.fromEntries
    ( Array.from
        ( map.entries()
        , ([ k, v ]) =>
            v instanceof Map
              ? [ k, toObject (v) ]
              : [ k, v ]
        )
    )
    
console .log (toObject (m))
// { a: 1
// , b: 2
// , c:
//     { d: 3
//     , e: 4
//     , f: { g: 6 }
//     }
// }

Otherwise, if the Map keys are complex objects and cannot be reliably coerced into a string, you'll have to come up with another mapping that preserves the key's actual value, such as -

const m =
  new Map
    ( [ [ 'a', 1 ]
      , [ 'b', 2 ]
      , [ 'c'
        , new Map
            ( [ [ 'd', 3 ]
              , [ 'e', 4 ]
              , [ 'f'
                , new Map ([[ 'g', 6 ]])
                ]
              ]
            )
        ]
      ]
    )
    
const toObject = (map = new Map) =>
  Array.from
    ( map.entries()
    , ([ k, v ]) =>
        v instanceof Map
          ? { key: k, value: toObject (v) }
          : { key: k, value: v }
    )
    
console .log (toObject (m))
// [ { key: "a", value: 1 }
// , { key: "b", value: 2 }
// , { key: "c"
//   , value:
//       [ { key: "d", value: 3 }
//       , { key: "e", value: 4 }
//       , { key: "f", value: [ { key: "g", value: 6 } ] }
//       ]
//   }
// ]
like image 55
Mulan Avatar answered May 15 '26 08:05

Mulan