I'm building a small component which displays information based on a currently selected object called metric
.
Metric Card Component
<aura:component implements="forceCommunity:availableForAllPageTypes" access="global">
<aura:attribute name="metricLabelList" type="String[]" default="[]"/>
<aura:attribute name="metric" type="SObject"/>
<aura:attribute name="metricObjects" type="SObject[]"/>
<aura:attribute name="selectedMetric" type="String" default="Clicks"/>
<aura:handler name="change" value="{!v.metricObjects}" action="{!c.onMetricObjectsChanged}"/>
<div class="wsm_metric-card wsm_box-shadow">
<lightning:buttonMenu aura:id="menu" onselect="{! c.selectOption }" class="wsm_select" label="{!v.selectedMetric}" variant="bare-inverse" alternativeText="Show menu">
<aura:iteration items="{!v.metricLabelList}" var="metricOpt">
<lightning:menuItem value="{!metricOpt}" label="{!metricOpt}" />
</aura:iteration>
</lightning:buttonMenu>
<div class="current-value slds-m-vertical_x-small">
<span class="metric-value">{!v.metric.current}</span>
</div>
<div class="past-value positive">
<span></span>
<span class="value-delta">{!v.metric.previous}</span><span class="percentage-delta"> (-6.72%)</span>
</div>
</div>
</aura:component>
I'm passing the attributes value from a parent component like this:
<c:Metric_Card metricLabelList="{!v.metricLabels}" metric="{!v.metrics[0]}" metricObjects="{!v.metrics}"></c:Metric_Card>
The idea is that the parent component makes a request, fetches the data and then just passes the values to the Metric Card so it displays the information.
In the MC component I have a button which I use to select a different value, look for that value in an array of objects and change the displayed information, however, when i change values, the array of objects metricObjects
is being modified without any instruction to do so.
This is the method I'm using when changing values in the button:
Metric Card Helper
selectOption: function(component, event) {
var selectedItem = event.getParam("value");
component.set("v.selectedMetric", selectedItem);
var metric = component.get("v.metricObjects").find(element => {
return element.label === selectedItem;
});
component.set("v.metric", metric);
}
What I get is the following:
After loading the component the first time, my array is correctly defined:
But after selecting a different value, the same array is modified and now shoes duplicate values or even undefined values (see the "Impressions" object twice now):
QUESTION:
Why is the metricObjects
array being modified after I select a different value from by button menu, since I'm only directly setting the value of the metric
object?