[SalesForce] Fetch Label of picklist value instead on API in lightning

Controller code

<div class="slds-form-element__control">        
                        <lightning:select name="customergroup" aura:id="conCountry" onchange="{!c.onControllerFieldChange}" label="Customer Group" value="{!v.accountRequest.SAH_ACCT_GRP__c}">
                            <aura:iteration items="{!v.customerGroupPicklist}" var="stat">
                                <aura:if isTrue="{!v.accountRequest.SAH_ACCT_GRP__c  == stat.value}">
                                    <option text="{!stat.label}" value="{!stat.value}" selected="true"/>
                                    <aura:set attribute="else">
                                        <option text="{!stat.label}" value="{!stat.value}"/>
                                    </aura:set>
                                </aura:if>
                            </aura:iteration>
                        </lightning:select>
                    </div>

I have the following piece of code in my JS controller. The below code is called onchane

var controllerValueKey = event.getSource().get("v.value");

Here the above code is called when picklist value is changed. Here var is correctly pickling up the API value of a picklist field which I have chosen. The API name and labels are different for my picklist values.

customerGroupPicklist is populated in doinit

What I want is the label instead.

Can I do this in my JS?

Best Answer

To get the label, you're simply going to need to find the correct label based on the value. Here's one way you can do that:

var value = event.getSource().get("v.value"),
    labelForValue = component.get("v.customerGroupPicklist")
    .reduce( (a, v) => a || (v.value == value? v.label: ""), "");

Where "reduce" is an array function that is used to reduce the values of the array to a single value, in our case, the label that we're interested in looking for. This isn't the only possible solution, but just one of several that would work.

Related Topic