I have a fetch API that returns an array of objects, and within those objects are nested arrays and other objects. My goal is to filter out only the objects that contain a specific value. Specifically, I want to retrieve objects with an id of 11 from the productLines key.
The "productLines" key holds an array of objects.
Below is the code snippet I am using:
<script>
fetch('https://swagapi.coburns.com/api/fd/test/GetBranches')
.then((response) => response.json())
.then((data) => {
for(i = 0; i < data.length; i++) {
if(data[i].productLines[0].id === 11) {
console.log(data[i])
}
}
})
</script>
Although the current implementation only displays one result in the console, this single result does indeed have an id of 11 from the productLines key. However, I expect there to be multiple results.
Here is a sample of the initial response data obtained from the fetch API. The response includes over 25 objects, but not all of them include an id of 11 within their respective productLines:
[
{
"id": 5,
"url": "https://www.coburns.com/abitasprings",
"name": "Abita Springs",
"phone": "(985) 892-0381",
...
"productLines": [
{
"id": 1,
"name": "Appliances",
...
},
{
"id": 4,
"name": "HVAC - Heating, Ventilation, and Air Conditioning",
...
},
{
"id": 7,
"name": "Plumbing",
...
},
{
"id": 8,
"name": "Pipes, Valves, & Fittings",
...
},
{
"id": 9,
"name": "Kitchen & Bath Showroom",
...
},
{
"id": 11,
"name": "Waterworks",
...
}
],