Search code examples
javascriptsalesforce-lightning

String search with all fields of array of objects


I have list/array of objects, it is aligned in a table. I got to implement a search functionality irrespective of any specific field. In other words, whatever I search in the search text box if any field value of the table contains or matches with the string, It should display those records.

I have written a code to implement this functionality. But I feel it is not efficient in terms of the algorithm.

Input : <br/>
1. List of objects : [{ id : 1 ,  name : 'abc' , phone : 1234}, { id : 2 ,  name : 'abd' , phone : 3456} , { id : 3 ,  name : 'xyz' , phone : 5678}]
2. Field Api Names = ['id','name','phone']
3. Search string: '3'

Output: 
All 3 objects in the list must be the result. As phone number contains the number 3 in List[0] and List[1] + Id field of List[2] contains value 3.

Code :

function searchRecord(fieldApiList,records,searchStr){
    var filteredResults = []
    for(var i = 0 ; i < records.length ; i++){
        for(var j = 0 ; j < fieldApiList.length ; j++){
            var filedApi = fieldApiList[j];
            if(records[i].hasOwnProperty(filedApi)){
                var data = String(records[i][filedApi]).toLowerCase();
                if( data.includes(searchStr.toLowerCase())){
                    filteredResults.push(records[i]);
                }
            }
        }
    }
    return filteredResults;
}

// Invoke the method
var records = [
           { id : 1 ,  name : 'abc' , phone : 1234}, 
           { id : 2 ,  name : 'abd' , phone : 3456}, 
           { id : 3 ,  name : 'xyz' , phone : 5678}
];
var fieldApiList = ['id','name','phone'];
var searchStr = '3';
var searchResults = searchRecord(fieldApiList,records,searchStr)

I need to what is the best search functionality to search on all the fields of a list of objects. The functionality is for a lightning component of salesforce


Solution

  • I guess you want to compare everything as a string, so you might consider filter with a suitable test function:

    var records = [
      { id : 1 ,  name : 'abc' , phone : 1234}, 
      { id : 2 ,  name : 'abd' , phone : 3456}, 
      { id : 3 ,  name : 'xyz' , phone : 5678}
    ];
    
    function findInValues(arr, value) {
      value = String(value).toLowerCase();
      return arr.filter(o =>
        Object.entries(o).some(entry =>
          String(entry[1]).toLowerCase().includes(value)
        )
      );
    }
    
    console.log(findInValues(records,  3));
    console.log(findInValues(records, 'a'));
    console.log(findInValues(records, 'z'));
    console.log(findInValues(records, 567));