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
jrvjrv 

How to iterate through list of sbject in JS controller

I've got the following Apex method
 
@AuraEnabled(Cacheable=true)
    public static List<Group> getPublicGroups(String name){
        String wildcardName = '%' + name + '%';
        return [SELECT Id, Name FROM Group WHERE Name LIKE :wildcardName];
    }
And I've got the following JS:
 
handleSearchGroupSearch(event) {
        getPublicGroups({name: this.template.querySelector('[data-id="searchName"]').value}).then(result => {
            for (let key in result) {
                alert(key.Name);
            }
        })
        .catch(error => {
            this.error = error;
        });
    }

The query returns one record: [{"Name":"Test Group","DeveloperName":"Test_Group","Id":"00G5w000005fBXREA4"}]

But my alert shows 'undefined'.  Any ideas what I'm doing wrong?
ANUTEJANUTEJ (Salesforce Developers) 
Hi jrv,

Can you try console logging the result and check if the value you are gettin is right or not and this is just a thought but in case if you are getting right value can you try stringifying the response, try checking the below link:

>> https://salesforce.stackexchange.com/questions/175170/parse-a-json-and-use-it-in-lightning/204551

in case if this helps can you please choose this as the best answer so that it can be used by others in the future.

Regards,
Anutej
jrvjrv
Not sure why, but updating the for loop to the following resolved my issue:
 
for (var i = 0; i < result.length; i++) {
                alert(result[i].Name);
            }