[英]How to filter nested JSON children objects and return result Angular 8
I am getting API response inside filterchildrenByRegion
() function,我在filterchildrenByRegion
() function 中得到 API 响应,
I want to remove those object which are not matching with the selected Region and return all data as it is.我想删除那些与所选区域不匹配的 object 并按原样返回所有数据。
Ex 1 - If i will pass '1UL Africa'
inside changeRegion() function,than it will return data as my expected output 1 .例 1 -如果我将在 changeRegion() function 中传递'1UL Africa'
,那么它将按照我的预期返回数据 output 1 。
Ex - 2 - If i will pass 'South Africa"'
inside changeRegion() function,than it will return data as my expected output 2 . Ex - 2 -如果我将在 changeRegion() function 中通过'South Africa"'
,那么它将按照我的预期返回数据 output 2 。
changeRegion(){
this.newRegion = this.filterchildrenByRegion('1UL Africa');
}
filterchildrenByRegion(region){
this.data = [
{
"name": "Africa",
"children": [
{
"name": "Test1",
"region": "1UL Africa"
},
{
"name": "Test2",
"region": "South Africa",
},
{
"name": "Test3",
"region": "New Test",
}
]
},
{
"name": "Europe",
"children": [
{
"name": "Test4",
"region": "1UL Africa"
},
{
"name": "Test5",
"region": "Test Europe"
}
]
}
];
return this.data.filter(x => x.children.map(child => child.region).includes(regionName));
};
Expected OutPut1预期输出1
result = this.data = [
{
"name": "Africa",
"children": [
{
"name": "Test1",
"region": "1UL Africa"
}
]
},
{
"name": "Europe",
"children": [
{
"name": "Test4",
"region": "1UL Africa"
}
]
}
];
Expected OutPut 2预计 OutPut 2
result = this.data = [
{
"name": "Africa",
"children": [
{
"name": "Test1",
"region": "1UL Africa"
}
]
}
];
Here is a sample that will work for your case这是一个适用于您的案例的示例
return this.data.map((x) => {
const childrenFulfillingTheSearch = x.children.filter(c => c.region.includes(region));
if (childrenFulfillingTheSearch.length === 0) {
return undefined; //this country has no children fulfilling the requirements
}
return {
...x,
children: childrenFulfillingTheSearch
};
})
.filter(x => x !== undefined);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.