Home > Software engineering >  How do I access values from a Map object in a loop?
How do I access values from a Map object in a loop?

Time:11-23

I have an object called dataLookup, the contents of which are https://pastebin.com/MG4xB8ht. This is what one item looks like in it:

    {
        "key": "Andaman & Nicobar",
        "value": {
            "state": "Andaman & Nicobar",
            "fcra_registered": 8,
            "total": 140
        }
    },

I want to access the total value for each key and assign that to a prop in another component. I have this:

z={(d) => dataLookup.get(d["state"])["total"]}

This gives me an error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'total')

What am I doing wrong and how can I fix it?

Update: I've added a working REPL of the entire issue. You can see the error in the console. It is here, the error occurs on line 62.

CodePudding user response:

It looks like LayerCake is expecting an array of objects so a Map isn't really going to help here. Based on the documentation you should probably get an array of objects each of which comprises just its value object:

const dataLookup = arr.map(obj => obj.value);

And then add that array to the Svelte component:

<LayerCake
  data={dataLookup}
  // etc
</LayerCake>

CodePudding user response:

The error was that two keys were misplaced (Odisha vs Orissa). It has been corrected and the above code is correct.

Additionally, I added in ?.[colorKey] instead of [colorKey] in this scenario so it doesn't throw an error.

CodePudding user response:

let list = [{
        "state": "Andaman & Nicobar",
        "fcra_registered": 8,
        "total": 140
}]

 let map1 = new Map()
 list.map(item => map1.set(item.state,item.total))

console.log(map1.get('Andaman & Nicobar'))

CodePudding user response:

I would just loop over each item and perform the logic:

myData.forEach(item => myProp = item.value.total);

  • Related