Reputation: 4250
I have a search field where user can type any word to get the desired result. my object looks below
[{
"parentid":100,
"parentname":"A",
"child" : [
{
"childid": 1,
"childname": "X1",
},
{
"childid": 2,
"childname": "X2",
}]
},
{
"parentid":200,
"parentname":"B",
"child" : [
{
"childid": 3,
"childname": "X3",
},
{
"childid": 4,
"childname": "X4",
}]
}
]
If the search value is X4
, I should about to get below result
{
"parentid":200,
"parentname":"B",
"child" : [
{
"childid": 3,
"childname": "X3",
},
{
"childid": 4,
"childname": "X4",
}]
}
what I tried so far is
//this works if user search for parentname
onSearchChange(searchValue: string): void {
this.result = this.originalList.filter(f=>f.parentname.indexOf(searchValue) !== -1);
}
//I tried below to search for parentname or childname, but no luch
onSearchChange(searchValue: string): void {
this.result = this.originalList.filter(f=>f.parentname.indexOf(searchValue) !== -1 ||
f.child.foreach(y=>y.childname.indexOf(searchValue) !== -1));
}
Upvotes: 1
Views: 446
Reputation: 710
let arr= [{
"parentid":100,
"parentname":"A",
"child" : [
{
"childid": 1,
"childname": "X1",
},
{
"childid": 2,
"childname": "X2",
}]
},
{
"parentid":200,
"parentname":"B",
"child" : [
{
"childid": 3,
"childname": "X3",
},
{
"childid": 4,
"childname": "X4",
}]
}
];
let filteredArray = arr.filter((element) => element.child.some((child) => child.childname == "X4"));
console.log(filteredArray);
Upvotes: 1
Reputation: 5972
this.result = this.originalList.filter(f =>
f.parentname.includes(searchvalue) ||
f.child.some(c => c.childname.includes(searchvalue))
);
Upvotes: 1