Home » Javascript » Building a “queryable” javascript/JSON object

Building a “queryable” javascript/JSON object

Posted by: admin August 19, 2018 Leave a comment


I want to build an object that’s query-able by multiple parameters. The way I came up with stores data in spans with data attributes and “searching” with jQuery works, but I don’t like it.

For a quick demonstration, I keep my “data” like this:

<span data-color="red blue" data-name="bill" data-value="47"></span>
<span data-color="blue green white" data-name="jane" data-value="13"></span>
<span data-color="red" data-name="mary jack" data-value="35"></span>
<span data-color="green" data-name="bill" data-value="43"></span>
<span data-color="white" data-name="steve" data-value="123"></span>

So if I wanted to match all values with color “red”, I could just do:


If I wanted to match all named “bill” and color “green”, I would search like this


While this feels kind of clever, it also feels kind of hacky, tricking Javascript into queries with CSS selectors. Is there a better way that I can store and access the data? Requests could be numerous so I want it fast and not making an http request to query the data server-side. And in my situation, there could be hundreds of entries to search (another reason why I don’t like the CSS selector route).