使用对象数组的所有字段进行字符串搜索

String search with all fields of array of objects

我有 list/array 个对象,它们在 table 中对齐。无论任何特定领域,我都必须实现搜索功能。换句话说,如果 table 的任何字段值包含或匹配字符串,无论我在搜索文本框中搜索什么,它都应该显示这些记录。

我已经编写了代码来实现这个功能。但我觉得它在算法方面效率不高。

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.

代码:

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)

我需要什么是最好的搜索功能来搜索对象列表的所有字段。 该功能适用​​于 salesforce

的闪电组件

我猜您想将所有内容都作为字符串进行比较,因此您可以考虑使用 filter 和合适的测试函数:

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));