I have an apex list which returns a result of SOQL.
List<Account> List1=[select Name, Phone from Account where Name=:actName];
This method is being called from a JS file of my Lightning Web Component and the result is being saved in an array.
@wire(getAccounts,{actName:'$accountName'})
retrieveAccouts({error,data}){
if(data){
this.accountList = data;
}
else if(error){
}
}
I have a row of this account selected on UI and the Name of selected account. I want to search other details of that account in this array (accountList). How do I achieve this?
I tried to use find() method on the array but did not work. What else can be used? What condition should be used if I use filter() on this array?
filter takes a function that should return true (truthy) or false (falsey) but the conditions are whatever's needed.
If the condition was we needed to filter Account Names containing 'Bob' we could:
this.accountList = [{Name: 'Alice'}, {Name: 'Bob1'}, {Name: 'Bob2'}]
const bobs = this.accountList.filter(acc => acc.Name.includes('Bob'))
console.log(bobs) // [{ Name: "Bob1" }, { Name: "Bob2" }]
A gotcha that came to mind is case sensitivity and that the data from SOQL is always as the Field API Name / Developer Name is. Above I use Name like Account.Name but other fields like AccountNumber can be camel case and custom fields need the __c etc (Custom_Field__c). You can turn on debugging in Salesforce or you can console out the data to see exact field names by stringifying, parsing then logging out like:
console.log( JSON.parse( JSON.stringify( { list: this.accountList } )))
find is very similar but instead of returning an Array, it returns the first Object that's true/truthy:
this.accountList = [{Name: 'Alice'}, {Name: 'Bob1'}, {Name: 'Bob2'}]
const bob = this.accountList.find(acc => acc.Name.includes('Bob'))
console.log(bob) // { Name: "Bob1" }