I am getting API response inside getClusterByName()
function,
I want to search array of object based on region value which i am passing from changeRegion
function.
for ex - if i will pass '1UL Africa'
or 'New Test' or 'South Africa'
inside changeRegion
() function,
than it will return this specific object in result from list of array.
Expected Output :
result = [
{
"name": "Africa",
"children": [
{
"name": "Test1",
"region": "1UL Africa"
},
{
"name": "Test2",
"region": "South Africa",
},
{
"name": "Test3",
"region": "New Test",
}
]
}
];
changeRegion(){
this.newRegion = this.getClusterByName('South Africa');
}
getClusterByName(clusterName){
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.region === clusterName);
};
CodePudding user response:
You're pretty close. Basically, you will have to modify the filter condition.
From:
return this.data.filter(x => x.region === clusterName);
To something like this:
return this.data.filter(x => x.children.map(child => child.region).includes(clusterName));
What we're doing with this is: Create a list of all child region, validate the name is included (we transformed the list of objects into the list of strings to compared. SO, it'd be easier)
Finally, the result would be:
getClusterByName = (clusterName) => {
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(clusterName));
};
CodePudding user response:
return this.data.filter(x => x.children.some(z => z.region === clusterName))
You can check if at least one item check a condition in an array with some.