I am trying to filter/search in a deeply nested array of subarrays
In order to explain my problem it is better to show the array structure first.
const arr = [
[
{
title: "title 1",
city: [
{
"0": "London"
},
{
"1": "LA"
}
]
},
{
title: "Title 2",
city: [
{
"0": "New York"
},
{
"1": "London"
}
]
}
],
[
{
title: "Title 3",
city: [
{
"0": "Paris"
}
]
},
{
title: "title 4",
city: [
{
"0": "London"
}
]
}
]
];
As you see, in this nested Array there is a city
array of of key value pair objects
and my task is to search value
in this city
Array and return only first matching object of every subArray without flattening.
So, let’s say the filter keyword
is London
, I want to return the first matching object of every subArray which inlcudes that filter keyword
.
So here answer would be
const filteredArr = [
[
{
title: "title 1",
city: [
{
"0": "London"
},
{
"1": "LA"
}
]
}
],
[
{
title: "title 4",
city: [
{
"0": "London"
}
]
}
]
];
As you can see from first subArray only first object is returned, even though second object which has a title 2
also includes a value of London
in city
array.
I know that I can get the first matching object with find
method like this:
const filteredCity = city.find((obj) => Object.values(obj)[0] === "London");
But how to combine and get the desired array?
I am sorry if couldn’t explain my Problem properly. Let me know if something is not clear.
Any help will be appreciated.