gpt4 book ai didi

jquery - 在 jQuery 中过滤具有多个记录 ID 的分层 JSON 数据

转载 作者:行者123 更新时间:2023-12-01 06:01:26 26 4
gpt4 key购买 nike

引用以下链接:

https://stackoverflow.com/posts/4391119/revisions

Filter JSON Data with multiple record IDs in jQuery

如果 JSON 中有分层数据怎么办?我已经尝试在该 filterStore 函数中进行修改。但没有成功。你能帮我吗?

当前的filterStore是这样的:

var filter = {
"brand_id": [1,2,3],
"productname": new RegExp('(.*?)', 'gi'),
"price": new RegExp('.*?', 'gi')
};

function filterStore(dataStore, filter) {
return $(dataStore).filter(function(index, item) {
for( var i in filter ) {
if(filter[i] instanceof Array){
if($.inArray(parseInt(item[i],10),filter[i]) == -1)
return null;
else
continue;
}
if( ! item[i].toString().match( filter[i] ) ) return null;
}
return item;
});
}

但是 json 响应是这样的:

[
{
"brandInfo": {
"brand": "Lg",
"productname": "Microwave",
},
"prodInfo": {
"size": "1.5 ltr",
"price": 200,
"color": "black"
},
"Category": "Electronic",
"shop": "Walmart"
}
{
"brandInfo": {
"brand": "Samsung",
"productname": "Microwave",
},
"prodInfo": {
"size": "1.5 ltr",
"price": 250,
"color": "Ivory"
},
"Category": "Electronic",
"shop": "Walmart"
}
{
"brandInfo": {
"brand": "Toshiba",
"productname": "Microwave",
},
"prodInfo": {
"size": "1.6 ltr",
"price": 310,
"color": "Silver"
},
"Category": "Electronic",
"shop": "Walmart"
}
{
"brandInfo": {
"brand": "Hitachi",
"productname": "Microwave",
},
"prodInfo": {
"size": "1.5 ltr",
"price": 280,
"color": "black"
},
"Category": "Electronic",
"shop": "Walmart"
}
]

Joy,你能帮我为这样的分层数据设置过滤器吗?新功能filterStore?

最佳答案

首先重写过滤器以反射(reflect)嵌套结构。

var filter = {
"brandInfo": {
"brand_id": [1,2,3]
},
"prodInfo": {
"productname": new RegExp('(.*?)', 'gi'),
"price": new RegExp('.*?', 'gi')
}
};

现在您可以像这样编写过滤器代码(只需添加一个嵌套循环来循环访问外部属性,例如brandInfo)。

function filterStore(dataStore, filter) {
return $(dataStore).filter(function(index, item) {
for( var prop in filter ) {
if (item[prop] == null) return null;
for( var i in prop ) {
if (item[prop][i] == null) return null;
if(filter[prop][i] instanceof Array){
if($.inArray(parseInt(item[prop][i],10),filter[prop][i]) == -1) return null;
else continue;
}
if( ! item[prop][i].toString().match( filter[prop][i] ) ) return null;
}
}
return item;
});
}

就您示例中的数据结构而言,这应该有效。但请记住,此代码假设您的过滤器仅包含第二级嵌套属性。对于过滤嵌套属性的更通用的解决方案,您需要将过滤器逻辑放在单独的函数中并递归地使用它。

关于jquery - 在 jQuery 中过滤具有多个记录 ID 的分层 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11160419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com