How do I filter an object by object keys and values?

I have two arrays, one is a filter with a key and value, and one data.

const filter = [
   {key: "name", value: "foo"},
   {key: "url", value: "foobar.com"}
]

const data = [
   {name: "foo", url: "google.com", extra: "hello!"}, 
   {name: "foo", url: "foobar.com", extra: "hello!"}, 
   {name: "bar", url: "foobar.com", extra: "hello!"},
   {name: "foo", url: "foobar.com", extra: "goodbye!"}
]

I want to achieve a one-line filter option that does the following:

const filteredData = data. //doSomething();

console.log(filteredData) 

/** prints out: 
 * [{name: "foo", url: "foobar.com", extra: "hello!"},{name: "foo", url: "foobar.com", extra: "goodbye!"}]
 **/

The filter array is a dynamically changing list of keys and values. Currently, I have the name and url hardcoded through two Array.prototype.filter constants which check explicitly for the type and value, but I know for expandability and best practices, this isn’t ideal. Any help would be greatly appreciated. Thank you in advance.

78 thoughts on “How do I filter an object by object keys and values?”

Leave a Comment