简体   繁体   English

构建一个“可查询”的javascript / JSON对象

[英]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. 我想出的方式使用数据属性跨区域存储数据,并使用jQuery进行“搜索”,但是我不喜欢它。

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 如果我想匹配所有命名为“ bill”和颜色为“ green”的颜色,则可以这样搜索

$("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. 尽管这看起来很聪明,但也感觉很hacky,使用CSS选择器将Javascript诱骗到查询中。 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. 请求可能很多,因此我希望快速执行,而不要发出http请求来查询数据服务器端。 And in my situation, there could be hundreds of entries to search (another reason why I don't like the CSS selector route). 在我的情况下,可能要搜索数百个条目(这也是我不喜欢CSS选择器路由的另一个原因)。

Thanks! 谢谢!

Use an ordinary Javascript array of objects instead, and then use array methods to filter, iterate, and so on. 而是使用普通的Javascript对象数组,然后使用数组方法进行筛选,迭代等。 No jQuery needed. 无需jQuery。 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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