@synotech/utils
Version:
a collection of utilities for internal use
43 lines (39 loc) • 1.05 kB
text/typescript
import { isEqual, some } from 'lodash';
interface AnyObject {
[key: string]: any;
}
/**
* This function searches an array of objects for a query string
* @module searchObject
* @param {string} query - a string to search for
* @param {object} objects - an array of objects to search
* @return {object} {Array} a well structured json object
* @example
*
* searchObject('John', [{name: 'John Doe'}, {name: 'Jane Doe'}]) // returns [{name: 'John Doe'}]
*
*/
export function searchObject(query: string, objects: AnyObject[]): AnyObject[] {
try {
query = query.trim().toLowerCase();
const results: AnyObject[] = [];
for (let i = 0; i < objects.length; i++) {
for (const key in objects[i]) {
try {
if (objects[i][key]?.toLowerCase().includes(query)) {
if (
!some(results, (item) => isEqual(item, objects[i]))
) {
results.push(objects[i]);
}
}
} catch (error) {
// Handle potential errors here (optional)
}
}
}
return results;
} catch (error) {
return objects;
}
}