使用 $.grep 将数组数据与另一个数组匹配
尝试查看一个数组中的数据是否与另一个数组中的数据匹配。我有一个对象数组,就像这样 -
var ProductsList =
[
{"Name": "Product A"; "Rating": "3"},
{"Name": "Product B"; "Rating": "2"},
{"Name": "Product C"; "Rating": "1"},
];
然后我想将此产品列表与用户选择的值进行比较,这些值位于我根据他们通过复选框选择的值获得的数组中。因此,如果他们选择 1、2、3,则应显示所有产品,如果他们选择 1,则仅显示产品 A。
我尝试使用 $.grep 进行过滤,但遇到了通过数组值过滤的问题。作为示例,我们将用户文件管理器硬编码为所有值。
userFilterArray.Rating = [1, 2, 3];
function filter(ProductsList, userFilterArray)
filteredList = $.grep(ProductList, function(n) {
return (n.Rating == userFilterArray.Rating);
});
显然这不起作用,因为我正在比较 n.Rating (一个字符串)和一个数组,但我不确定在这种情况下如何将字符串与字符串进行比较。
grep 是最简单的方法吗?我应该使用 .each .each 的组合吗?也许两者都不是?
Trying to see if data in one array matches the data in another. I have an array of objects, like so -
var ProductsList =
[
{"Name": "Product A"; "Rating": "3"},
{"Name": "Product B"; "Rating": "2"},
{"Name": "Product C"; "Rating": "1"},
];
I then want to compare this product list with user selected values, which come in an array that I get based on the values they selected via checkboxes. So if they selected 1, 2, 3 - all products should be shown, if they selected 1 - then only product A is shown.
I tried to use $.grep to do the filtering but I'm running into an issue filtering via array values. Let's hard code the user filer to all values as an example.
userFilterArray.Rating = [1, 2, 3];
function filter(ProductsList, userFilterArray)
filteredList = $.grep(ProductList, function(n) {
return (n.Rating == userFilterArray.Rating);
});
Obviously this doesn't work as I'm comparing n.Rating which is a string to an array but I'm not sure how to compare the string to string in this case.
Would grep be the easiest way to do this? Should I use a combo of .each .each? Maybe neither?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
经过一系列语法和其他修复后,我认为这就是您所追求的:
DEMO: http://jsfiddle.net/vK6N9/
After a bunch of syntax and other fixes, I think this is what you're after:
DEMO: http://jsfiddle.net/vK6N9/