create a multi key object filter in javascript

To create a multi key object filter in JavaScript, you can use the filter method on an array of objects along with a custom filter function. The custom function should take an object as input and return a Boolean based on whether that object matches the filter criteria.

To match multiple keys, you can use logical operators like && and || to combine multiple filter conditions. Here's an example implementation:

index.tsx
// Sample data
const people = [
  { name: 'John', age: 29, city: 'London' },
  { name: 'Jane', age: 35, city: 'Paris' },
  { name: 'Mike', age: 20, city: 'New York' },
  { name: 'Lisa', age: 18, city: 'Sydney' }
];

// Function to filter objects based on multiple keys
function multiKeyFilter(arr, filters) {
  // Convert filters object to an array of key-value pairs
  const filterKeys = Object.keys(filters);

  // Filter the array of objects
  return arr.filter((obj) =>
    // Check if all filter criteria are met
    filterKeys.every((key) => {
      // Use a regular expression to match values
      if (typeof filters[key] === 'string') {
        const regex = new RegExp(filters[key], 'i');
        return regex.test(obj[key]);
      }
      // Use direct comparison for other types
      return obj[key] === filters[key];
    })
  );
}

// Example usage: filter people from London who are over 25 years old
const filteredPeople = multiKeyFilter(people, {city: 'London', age: '>25'});
console.log(filteredPeople); // Output: [{ name: 'John', age: 29, city: 'London' }]
1077 chars
32 lines

In this example, multiKeyFilter is a function that takes an array of objects (arr) and a filters object (filters) as input. The filters object should contain key-value pairs where the key is the object property to match and the value is the filter criteria (can be a string, number, or other type).

The function converts the filters object to an array of filter keys (filterKeys) and then uses the filter method on the input array to return a new filtered array. For each object in the input array, the function checks if all filter criteria are met using the every method on the filterKeys array.

Inside the every method, the function applies the filter criteria to each key-value pair. For string values, it creates a regular expression to perform a case-insensitive match using the RegExp constructor and then uses the test method to check if the string matches the filter value. For other types, it uses direct comparison (===) to check if the value matches the filter value.

Finally, the function returns the filtered array of objects.

gistlibby LogSnag