0

today I was trying to iterate and compare an array given from Apex to create a new one without repeated values, but I just couldn't. It was like my logic code was ignored.

Then I was reading in stackexchange that when you retrieve data from Apex you need to make a copy of the data before change it because otherwise you won't be able to change anything due to a 'read-only' or frozen data.

I tried with spread operator, map, slice, Object.assignment,JSON.parse(JSON.stringfy) (almost everything I know) but I didn't find a solution. Finally I filtered the values from Apex and It worked for me, but I still have the doubt of how can I proceed in this cases with LWC.

Here is my code, so If anyone know a solution or have faced the same issue, I'll be very gratefull!

Apex code:

@AuraEnabled(cacheable = false)
public static List<String> getPicklistValuesByProduct(string quoteId){
    List<QuoteLineItem> qli = [
        SELECT Product2.Family
        FROM QuoteLineItem
        WHERE QuoteId =:quoteId
    ];
    return qli;
}

LWC code:

myData = [];
myFormattedData = []
connectedCallback() {
    this.getSelectableValues();
}

getSelectableValues() {
    apexcall({quoteId: this.recordId}).then(data => {
        this.myData = data.map(element => ({...element}));
        this.setPicklistValues();
    }).catch(//error catch)
}

setPicklistValues() {
    this.myData.forEach(e =>{
        if (this.myFormattedData.length == 0) {
            this.myFormattedData.push(e)
        }
        if (myFormattedData.length > 0 && !this.myFormattedData.includes(e)) { 
            this.myFormattedData.push(e)
        }  
    })
}

Result = myFormattedData is not filtered, is just equal to the data given by the Server

3
  • 1
    parse(stringify()) has worked for me.
    – Keith C
    Commented Mar 16, 2022 at 15:28
  • @Julian Gutierrez Caligaris what does each of your "e" items look like in your this.myData array? a "string" or an object {id: something ...}?
    – glls
    Commented Mar 16, 2022 at 17:38
  • Yeah finally worked the parse(stringify) the problem was that I was filling the array with ({label:e,value:e}) to an checkbox, and for some reason that doesn't work fine. But when i filled the array with just the single row and then i formatted the data for the checkbox, It worked fine :). Thank you very much!! Commented Mar 16, 2022 at 19:57

1 Answer 1

2

JavaScript has a Set class, which is like an Array, but must contain unique values. Converting an array to a set and back to an array will remove duplicate values.

this.myData = new Array(new Set(this.myData));
1
  • 3
    You can also: [...new Set(this.myData)]
    – sfdcfox
    Commented Mar 16, 2022 at 17:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .