const array = [
{
id: "1",
children: [],
messages:[1, 'Text'],
entry: "Father",
},
{
id: "2",
entry: "Mother",
children: [
{entry: "John Jr"},
{entry: "Steven Jr"},
{entry: "Tim Jr"},
],
messages:[2, 'Text'],
},
{
id: "3",
entry: "Son",
children: [
{entry: "XXX Jr"},
{entry: "Steven Jr"},
{entry: "Tim Jr"}
],
messages:[3, 'Text'],
},
]
So what I want here is, when I do the search "Tim". I want the output to be
Case 1: When I search for Tim, I should get the object with id: 2 and id: 3 because Tim is an entry matching in both the objects. so I want to return the entire id: 2 and 3 object in the same order.
{
id: "2",
entry: "Mother",
children: [
{entry: "John Jr"},
{entry: "Steven Jr"},
{entry: "Tim Jr"},
],
messages:[2, 'Text'],
},
{
id: "3",
entry: "Son",
children: [
{entry: "XXX Jr"},
{entry: "Steven Jr"},
{entry: "Tim Jr"}
],
messages:[3, 'Text'],
}
Case 2: When I search for John, I should get second object as
{
id: "2",
entry: "Mother",
children: [
{entry: "John Jr"},
],
messages:[2, 'Text'],
}
Case 3: When I search for Steven, I should get id:2 and id:3 as
id: "2",
entry: "Mother",
children: [
{entry: "John Jr"},
{entry: "Steven Jr"},
],
messages:[2, 'Text'],
},
{
id: "3",
entry: "Son",
children: [
{entry: "XXX Jr"},
{entry: "Steven Jr"},
],
messages:[3, 'Text'],
}
I used .filter() to filter the top level but this isn't checking the children.
array.filter((item) => item.entry.toUpperCase().includes(text.toUpperCase()));
Any help would be greatly appreciated as I'm totally lost with forEach here. Thanks in advance
array.filter(). The callback function should search thechildrenarray for matching names.array.some().some()can useelement.entry.includes(name)wherenameis the name you're looking for.