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.

>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);

Leave a Reply