Best way to Search ALL Terms in Array of Objects
Solution 1:
Map the array of devices to a new array, where one item is the device, and one is an array of strings composed from the keys and values (with the deviceId
excluded with rest syntax).
Then, all you have to do is filter that array by whether .every
one of the search terms is included in .some
of those strings.
const DeviceDtos = [
{
deviceId: 1,
deviceName: "Device0000",
hwModelName: "Unassigned",
deviceTypeName: "Unassigned",
serviceTag: "A1A"
},
{
notincluded: 'notincluded'
}
];
const devicesAndStrings = DeviceDtos.map(
({ deviceId, ...obj }) => [obj, Object.entries(obj).flat()]
);
const searchTerms = ["hwModel", "A1A"];
const foundDevices = devicesAndStrings
.filter(([, strings]) => searchTerms.every(
term => strings.some(
string => string.includes(term)
)
))
.map(([obj]) => obj);
console.log(foundDevices);