简体   繁体   中英

Building a “queryable” javascript/JSON object

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:

$("span[data-color~='red']").each(...);

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

$("span[data-color~='green'][data-name~='bill']").each(...);    

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).

Thanks!

Use an ordinary Javascript array of objects instead, and then use array methods to filter, iterate, and so on. No jQuery needed. For example:

 const arr = [ { colors: ['red', 'blue'], name: 'bill', value: 47 }, { colors: ['blue', 'green', 'white'], name: 'jane', value: 13 }, { colors: ['red'], name: 'mary jack', value: 35 }, { colors: ['green', 'blue'], name: 'bill', value: 88 }, ]; const reds = arr.filter(({ colors }) => colors.includes('red')); console.log(reds); const greenBills = arr.filter(({ colors, name }) => colors.includes('green') && name === 'bill' ); console.log(greenBills); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM