function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
naveen reddy 19naveen reddy 19 

How to get the length of a attribute of type " map" in lightning controller

Hi ,

 How to get the length of a attribute of type " Map" from lightning controller.

Component:
<aura:attribute name="IndexMap" type="Map" default="{ 'Draft':1, 'Pending':2, 'NeedInfo':3, 'Resolved':4, 'Closed':5}"/>

Controller:
var myMap= component.get("v.IndexMap");
        alert(myMap.length);

The above code result to "undefined". Actually I have to get "5" as myMap has 5 elements.  Can you please help in getting this.

Thanks in advance.

Regards,
Naveen.
NagendraNagendra (Salesforce Developers) 
Hi Naveen,

A collection that maps keys to values. A map can’t contain duplicate keys. Each key can map to at most one value. Defaults to an empty object, {}. Retrieve values by using cmp.get("v.sectionLabels")['a'].

Please try below code and let us know if it works.

Component:
<aura:attribute name="IndexMap" type="Map" default="{ 1: 'Draft', 2: 'Pending', 3:'NeedInfo', 4:'Resolved', 5:'Closed'}"/>
Controller:
var myMap= component.get("v.IndexMap");
        alert(myMap.size);
Hope this helps.

Mark this as solved if it;s resolved.

Regards,
Nagendra.

 
Ajay K DubediAjay K Dubedi
Hi Naveen,
For getting the length of a attribute of type " Map " from Lightning Controller.

Please try below code and let us know if it works.

Component:
<aura:component >
 <aura:attribute name="IndexMap" type="Map" 
                    default="{ 'Draft':1, 'Pending':2, 'NeedInfo':3, 'Resolved':4, 'Closed':5}"/>
 <ui:button label="Length is "
               press="{!c.getLength}"/>
</aura:component>
Controller :
({
 getLength : function(component, event, helper) {
  var myMap= component.get("v.IndexMap");
  var count = 0;
  var i;
   for (i in myMap){
    if(myMap.hasOwnProperty(i)){
       count++;
     }
   }
       alert(count);
 }
})
I hope, It will help you. 
Regards,
Ajay
Please mark my answer as a solution if it is helpful.
Utilization Matrix 2Utilization Matrix 2
this one was really helpful