I have the following javascript search function
function findMatches(srchFor, srchList, keyobj) {
return srchList.filter(srchList => {
const regex = new RegExp(srchFor, 'gi');
return srchList[keyobj].match(regex);
});
}
Example Json object to search;
Customers = {"entity": [{
"Id": "ACB123",
"OrderId": 0,
"EntityType": "CU",
"Name": "ABC Company",
"Address1": "123 Main Street",
"Address2": null,
"City": "CROCKETT",
"State": "CA",
"Zip": "94525",
"Country": "USA",
"Phone": null,
"Email": null,
"Contact": null,
"IdCodeQual": null,
"IdCode": null,
"LastUpdate": "2021-04-06T17:31:02",
"Attrib01": null,
"Attrib02": null,
"Attrib03": null,
"Attrib04": null,
"Attrib05": null
},
{
"Id": "WFCH",
"OrderId": 0,
"EntityType": "CU",
"Name": "World's Finest Company",
"Address1": "100 State Street",
"Address2": null,
"City": "Chicago",
"State": "IL",
"Zip": "60632",
"Country": "USA",
"Phone": "773-555-1200",
"Email": null,
"Contact": null,
"IdCodeQual": null,
"IdCode": null,
"LastUpdate": "2016-09-20T12:59:25",
"Attrib01": null,
"Attrib02": null,
"Attrib03": null,
"Attrib04": null,
"Attrib05": null
}
]
}
This function works fine as is for searching one field with usage as
var result = findMatches('ABC',Customers,'Id')
What I would like to be able to do is pass in more than one field to search as such
var result = findMatches('ABC',Customers,['Id','Name'])
so I can search both the name and Id fields for a match without having to have an explicitly defined search. I'd like the same function to work for
var result = findMatches('ABC',Customers,['City','Address1'])
This solution filters array depending on several fields
const Customers = {
entity: [
{
Id: "ACB123",
OrderId: 0,
EntityType: "CU",
Name: "ABC Company",
Address1: "123 Main Street",
Address2: null,
City: "CROCKETT",
State: "CA",
Zip: "94525",
Country: "USA",
Phone: null,
Email: null,
Contact: null,
IdCodeQual: null,
IdCode: null,
LastUpdate: "2021-04-06T17:31:02",
Attrib01: null,
Attrib02: null,
Attrib03: null,
Attrib04: null,
Attrib05: null,
},
{
Id: "WFCH",
OrderId: 0,
EntityType: "CU",
Name: "World's Finest Company",
Address1: "100 State Street",
Address2: null,
City: "Chicago",
State: "IL",
Zip: "60632",
Country: "USA",
Phone: "773-555-1200",
Email: null,
Contact: null,
IdCodeQual: null,
IdCode: null,
LastUpdate: "2016-09-20T12:59:25",
Attrib01: null,
Attrib02: null,
Attrib03: null,
Attrib04: null,
Attrib05: null,
},
],
};
//Returns what recieves
const pass = (input) => input;
const findInArray = (array, searchRegExp, fields) => {
return array.filter((item) => {
// returs true if at least one of fields value match to regexp
return fields.map((field) => searchRegExp.test(item[field])).some(pass);
});
};
console.log(findInArray(Customers.entity, /ACB/, ["Id", "Name"]));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.