Populating a string with recordId's from selectedRows in lightning datatable include duplicates

I have a lightning datatable with checkboxes enabled, and I am trying to get a list of record ID's in a string so that I can use it to prepopulate a call report that it creates with the information from the selected rows.

My event handler for getSelectedData is triggered when a user clicks on a checkbox or more.

        const selectedRows = event.detail.selectedRows;
        for (let i = 0; i<selectedRows.length; i++ ) {
            this.selectedIds += selectedRows[i].Id + ',';    
        }

However, I think every time I click on a checkbox this method is called, therefore putting in duplicates of the Id's. How can I ensure there are no duplicates? I tried using a set but it didn't work out well, or I think I used it wrong.

Answers 2

  • What you're trying to do is a one-liner in JavaScript. By the way, as glls stated, you never reset the string when you add/remove elements, so it gets duplicated every time. Here's the efficient version:

    getSelectedData(event) {
        this.selectedIds = event.detail.selectedRows.map(row => row.Id).join(',');
    }
    

    Also note that you probably really just want an Array, not a string of joined values, which is simply:

    getSelectedData(event) {
        this.selectedIds = event.detail.selectedRows.map(row => row.Id);
    }
    

    The Array.prototype.map function is what allows this to work efficiently.


  • the reason you are getting duplicates is because you are simply appending id's to a string within an iteration. (your for loop)

    you probably want to clear the this.selectedIds at the beginning of your method to ensure you don't constantly increase the size of your string and add duplicate info.


Related Questions