[英]Filter Nested array of objects in angular java script
Hi I am Having following array.嗨,我有以下数组。 I want to filter this array depending on user input.I have search it on internet gone through many solutions on stack overflow i have also gone through documentation of array but i didn't get any solution.
我想根据用户输入过滤这个数组。我在互联网上搜索它,通过了许多关于堆栈溢出的解决方案,我也浏览了数组的文档,但我没有得到任何解决方案。 Please Help...
请帮忙...
{
"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 "
}
}
]
}
]
}
]
}
I want to apply filter on 'categoryName' , 'SubCategoryName' , 'DisplayName' , 'ItemName'我想对 'categoryName' 、 'SubCategoryName' 、 'DisplayName' 、 'ItemName' 应用过滤器
for example if I search 'choco almond' (which is 'ItemName') then the resultant array should be like例如,如果我搜索“巧克力杏仁”(即“ItemName”),那么结果数组应该类似于
{
"data": [
{
"categoryId": "2",
"categoryName": "Markers",
"subcat": [
{
"SubCatId": "2",
"SubCategoryName": "Premium Cakes I",
"item": [
{
"DisplayName": "choco almond 500gms",
"ItemData": {
"Id": "52",
"ItemName": "choco almond "
}
}
]
}
]
}
]
}
if i search 'Pens' (which is 'categoryName') then thw resultant array should be like如果我搜索“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 "
}
}
]
}
]
}
]
}
What you can do is do a filter inside a filter.你可以做的是在过滤器内做一个过滤器。
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)
Where variable "d" is the json/object.其中变量“d”是 json/object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.