How to convert json to map?

  • 0
    Hey. I have a json with a nested structure
    {
      "room": {
        "80-c4-48-84-79": " Federal research and production center ",
        "73-b3-49-af-9d": " dgru",
        "04-d2-45-86-6a": "Main",
        "d0-51-41-bf-4f": " Publications",
        "c5-3c-4d-83-4f": " news",
        "7d-ae-46-a0-25": "Contacts",
        "8f-01-4b-81-4e": "Certification center",
        "56-32-40-82-1a": "1959",
        "27-63-47-b9-1c": "2019",
        "a7-34-46-b8-38": " Moscow",
        "42-29-4c-bb-df": " text",
        "67-8b-47-b1-34": "example"
      }
    }


    how to convert it to Map?
    There is such an example, but I can't convert it to my json
    const personsJson = `{"1":{"firstName":"Jan","lastName":"Kowalski"},"2":{"firstName":"Justyna","lastName":"Kowalczyk"}}`;
    const personsObject = JSON.parse(personsJson);
    const personObjectEntries = Object.entries(personsObject);
    const personObjectEntriesNumberKeys = personObjectEntries.map(person => {
        person[0] = parseInt(person[0]);
        return person;
    });
    const personsMap = new Map(personObjectEntriesNumberKeys);
    for (const key of personsMap.keys()) {
        console.log(typeof key)
    }

    I would be grateful for your help
    JavaScript Anonymous, Feb 8, 2019

  • 1 Answers
  • 0
    a = {
    "room": {
    "80-c4-48-84-79": " Federal research and production center ",
    "73-b3-49-af-9d": " dgru",
    "04-d2-45-86-6a": "Main",
    "d0-51-41-bf-4f": " Publications",
    "c5-3c-4d-83-4f": " news",
    "7d-ae-46-a0-25": "Contacts",
    "8f-01-4b-81-4e": "Certification center",
    "56-32-40-82-1a": "1959",
    "27-63-47-b9-1c": "2019",
    "a7-34-46-b8-38": " Moscow",
    "42-29-4c-bb-df": " text",
    "67-8b-47-b1-34": "example"
    }
    }
    d = new Map(Object.keys(a.room).map(x=>[x, a.room[x]]))




    or write a recursive function if you need to iterate over nested objects:

    var remap = x=>new Map(Object.keys(x).map(y=>[y,(typeof(x[y])=="object")?remap(x[y]):x[y]]))
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!