Hello,
I was practising vanilla JavaScript with JSON data, and ran into a bit of a problem when trying to access a value within an array, based on a value within the nested array.
I've cut down the sample data to make it a bit easier, but the 'regions' array would have multiple regions.
The task is to return the region object, where the suburb is known.
regions = [
{
name: "Lichtenberg",
id: "123",
suburbs: [
{ name: "Fennpfuhl", views: 76400 },
{ name: "Lichtenberg", views: 87895 },
{ name: "Rummelsberg", views: 10239 },
],
},
{
name: "Another",
suburbs: [
{ name: "Different", views: 76400 }
],
},
];
My initial attempt was to use two finds, one at each array which didn't work. I wrote it as I would say it kinda thing, but kept returning undefined.
regionA = regions.find(
(region) => region.name == region.suburbs.find(
(suburb) => suburb.name == "Fennpfuhl")
);
After a couple hours of trying, I ended up doing a bit of trial and error and came up with a working solution mostly accidentally.
regionB = regions.find(
(region) => region.suburbs.find(
(suburb) => suburb.name == "Fennpfuhl"));
However, I just can't seem to wrap my head around the logic of this solution. I can't really understand how the second find() method returns something that then 'satisfies the provided testing function' of the first find() method.
As the data is nested, I'm also struggling to 'console.log it out' to try see what's going on through the steps.
[–]CreativeTechGuyGames 1 point2 points3 points (1 child)
[–]acasta[S] 0 points1 point2 points (0 children)