[SalesForce] How to iterate a Map in Aura

I have a aura map attribute defined in my component file as below

<aura:attribute name="FilesNameMap" type="Map">

But i am not able to understand how to iterate this in the component file as we know that the < aura:iteration > will work on List but not for Map.

Below is the code which i tried to iterate the Map but couldn't succeed.

 <aura:iteration items="{!v.FilesNameMap}" indexVar="key" var="item">
                    //- logic                   
 </ aura:iteration>

Please let me know how can i iterate the Map in Aura component to fetch key and value pairs.

Thanks.

Best Answer

Pretty much all browsers support the JavaScript method Object.keys() which takes in an object and returns an array of just its keys. So you could have a second attribute of type String[] and set it in the controller equal to Object.keys(theMapYouWantToIterate). A bit more troublesome though is the fact that you can't actually look up that index of the map in Aura binding notation (e.g {!v.myMap[key]} doesn't work).

So if you need to iterate and use both the name and values, you might alternatively want to pass it to the controller as a list of objects (i.e. Map[]) where each object has a name and a value. If you have no choice but to start with a map in the controller, you can transform it to a list of objects something like this: var listOfObjects = Object.keys(myMap).map(function(key){return {name: key, value: myMap[key]} }).

Related Topic