javascript - 在角度java脚本中过滤嵌套的对象数组
问题描述
嗨,我有以下数组。我想根据用户输入过滤这个数组。我在互联网上搜索过很多关于堆栈溢出的解决方案,我也浏览过数组的文档,但我没有得到任何解决方案。请帮忙...
{
"data": [
{
"categoryId": "1",
"categoryName": "Pens",
"subcat": [
{
"SubCatId": "1",
"SubCategoryName": "Classic Cakes",
"item": [
{
"DisplayName": "Excellent 500gms",
"ItemData": {
"ItemName": "Excellent"
}
},
{
"DisplayName": "choco vanila 500gms",
"ItemData": {
"Id": "26",
"ItemName": "choco vanila "
}
}
]
},
{
"SubCatId": "2",
"SubCategoryName": "Classic Cakes2",
"item": [
{
"DisplayName": "xyz 500gms",
"ItemData": {
"ItemName": "xyz"
}
},
{
"DisplayName": "abc 500gms",
"ItemData": {
"Id": "26",
"ItemName": "abc vanila "
}
}
]
}
]
},
{
"categoryId": "2",
"categoryName": "Markers",
"subcat": [
{
"SubCatId": "2",
"SubCategoryName": "Premium Cakes I",
"item": [
{
"DisplayName": "choco caramel 500gms",
"ItemData": {
"Id": "65",
"ItemName": "choco caramel"
}
},
{
"DisplayName": "choco almond 500gms",
"ItemData": {
"Id": "52",
"ItemName": "choco almond "
}
}
]
}
]
}
]
}
我想在 'categoryName' 、 'SubCategoryName' 、 'DisplayName' 、 'ItemName' 上应用过滤器
例如,如果我搜索“choco almond”(即“ItemName”),那么结果数组应该是
{
"data": [
{
"categoryId": "2",
"categoryName": "Markers",
"subcat": [
{
"SubCatId": "2",
"SubCategoryName": "Premium Cakes I",
"item": [
{
"DisplayName": "choco almond 500gms",
"ItemData": {
"Id": "52",
"ItemName": "choco almond "
}
}
]
}
]
}
]
}
如果我搜索“Pens”(即“categoryName”),那么结果数组应该是
{
"data": [
{
"categoryId": "1",
"categoryName": "Pens",
"subcat": [
{
"SubCatId": "1",
"SubCategoryName": "Classic Cakes",
"item": [
{
"DisplayName": "Excellent 500gms",
"ItemData": {
"ItemName": "Excellent"
}
},
{
"DisplayName": "choco vanila 500gms",
"ItemData": {
"Id": "26",
"ItemName": "choco vanila "
}
}
]
},
{
"SubCatId": "2",
"SubCategoryName": "Classic Cakes2",
"item": [
{
"DisplayName": "xyz 500gms",
"ItemData": {
"ItemName": "xyz"
}
},
{
"DisplayName": "abc 500gms",
"ItemData": {
"Id": "26",
"ItemName": "choco vanila "
}
}
]
}
]
}
]
}
解决方案
你可以做的是在过滤器中做一个过滤器。
var filter = "Pens";
var result = d["data"].filter(c=>
c.categoryName==filter ||
c.subcat.filter(s => s.SubCategoryName == filter).length > 0 ||
c.subcat.filter(i => i.item.filter(it => it.ItemData.ItemName == filter).length > 0).length > 0
);
console.log(result)
其中变量“d”是 json/object。
推荐阅读
- bash - bash中的后进先出堆栈?
- javascript - Jquery推送到对象只有唯一的元素
- java - 如何修复 OpenJDK 64 位 OpenJDK 64 位服务器 VM 警告和禁用堆栈防护
- angular - 多个单选按钮选择
- spring-integration - Spring 集成 - 如何使消息在 jdbc 消息存储中存活,以防出现错误或/并在使用处理程序中关闭
- reactjs - 创建选择输入值,并能够在 React 中填写自己
- formatting - 如果单元格值与另一行 Power BI 不匹配,则突出显示行
- mysql - 是否可以使用行不唯一的 JPA 存储库删除单行?
- javascript - 给定按钮进入下拉列表
- flutter - 带有嵌入阴影和渐变的圆圈