Skip to content
Advertisement

How to use filter to search in multiple key values of objects in an array?

I have an array of wines containing objects with data for each wine:

JavaScript

I can figure out how to search — case insensitive — for a wine object, while specifying which key of the object to search in, like this:

JavaScript

Returns:

JavaScript

However, if var search = 'Winery 3' or var search = 'red' then it will obviously return no results, as it’s looking in the value of wineName of each object in the array.

So is there a way to use filter (or another method?) to search through all key values, or even better, multiple specified key values and return an array of the matching objects?

Something like:

JavaScript

Or am I completely barking up the wrong tree?

PS. I’m using Vue.js 2 so if there’s a better way inside vue then I’m all ears!

Advertisement

Answer

You could have a more generic function that will scan all the properties for the string. Loop through all property values with Object.values() and use some to bail out as soon as you have a match:

JavaScript

If you prefer to pass specific keys to search in:

JavaScript

Call as

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement