Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mapping JSON key-value directly into a Map (object.Entries does not work)

I have a simple object structure like this:

{
    "Anna": [
        "ItemA",
        "ItemB",
    ]
}

and I need to create a Map out of it. Using new Map(Object.entries(json)) results into the following, where the key is 0 instead of the name "Anna", which I would need:

  {
        "key": "0",
        "value": {
            "Anna": [
                "ItemA", "ItemB"
            ]
        }
    }

I know I could iterate through manually but I’m almost certain a single command exists for that.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can use the Map constructor with the Object.entries() method and then pass the resulting array of key-value pairs to the Map constructor. Here’s how you can do it:

const obj = {
  "Anna": [
    "ItemA",
    "ItemB",
  ]
};

const map = new Map(Object.entries(obj));

console.log(map);

This will output the following Map object with "Anna" as the key:

Map(1) {
  "Anna" => Array(2) [    "ItemA",    "ItemB"  ]
}

The Object.entries() method returns an array of key-value pairs from the object, like this:

[["Anna", ["ItemA", "ItemB"]]]

Passing this array to the Map constructor creates a new Map object with "Anna" as the key and the array ["ItemA", "ItemB"] as the value.

UPDATED ANSWER

const obj = {
  "Anna": [
    "ItemA",
    "ItemB",
  ],
  "John": [
    "ItemC",
    "ItemD",
  ],
  "Emily": [
    "ItemE",
    "ItemF",
  ]
};

const result = Object.entries(obj).map(([key, value], index) => {
  const newKey = index.toString();
  const newValue = {
    [key]: value
  };
  return {
    key: newKey,
    value: newValue
  };
});

console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading