Skip to content
Advertisement

JS search in object values

I have an array of homogeneous objects like so;

JavaScript

I’d like to search these objects’ values (not keys) with a keyword, and return an array of objects that contain the keyword in any of the values.

So for example, with a keyword r, I would get all the objects (“baR” in object #1, “loRem” in object #2 and “doloR” in object #3). With a keyword lo, I would get objects 2 and 3 (“LOrem” and “doLOr”), with a, I’d get objects 1 and 3, (“bAr” and “Amet”). With the keyword foo however, I would get an empty array, since “foo” is a key, and isn’t found in any of the values (unlike “bar”)… you get the idea.

How would I go about doing this? Thanks a lot in advance!

Advertisement

Answer

Something like this:

JavaScript

The results array will contain all matched objects.

If you search for ‘lo’, the result will be like:

JavaScript

NEW VERSION – Added trim code, code to ensure no duplicates in result set.

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