Home > Software design >  Why am I only returning one result while looping thru an array of data?
Why am I only returning one result while looping thru an array of data?

Time:08-12

I am using the fetch API that returns an array of objects and inside the returned object(s) are nested arrays and objects. My question is, how can I return objects that only include a specific value? In my case, I want to only return objects that have an id of 11 from productLines.

"productLines" is a key that contains an array of objects.

My code is as follows:

<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>

This is only returning 1 result in the console, the one result does in fact contain an id of 11 from productLines but there should be multiple results.

Here is an example of the initial response data from the fetch api, there are more than 25 returned objects but not all of them contain an id of 11 inside the productLines:

[
{
    "id": 5,
    "url": "https://www.coburns.com/abitasprings",
    "name": "Abita Springs",
    "phone": "(985) 892-0381",
    "altphone": null,
    "fax": "(985) 892-7391",
    "address": "21507 Bayou Court",
    "city": "Abita Springs",
    "state": "LA",
    "zip": "70420",
    "poAddress": null,
    "branchid": "35",
    "hasShowroom": false,
    "showroomOnnly": false,
    "showroomSchedule": "Monday to Friday, 7:00 am to 4:00 pm ",
    "afterHours": false,
    "additionalAfterHoursInfo": null,
    "counterSchedule": "Monday to Friday, 7:00 am to 5:00 pm",
    "counterAfterHours": false,
    "additionalCounterAfterHoursInfo": null,
    "openingYear": "2000",
    "manager": "Jimmy Bankston",
    "managerEmail": null,
    "assistantManager": null,
    "assistantManagerEmail": null,
    "generalManager": null,
    "showroomPhone": null,
    "showroomManager": "Jimmy Bankston",
    "showroomManagerEmail": "[email protected]",
    "webGroup": null,
    "lat": 30.4542560000,
    "lon": -90.0416490000,
    "openToPublic": false,
    "dc": 0,
    "region": null,
    "printer": null,
    "notes": null,
    "publicPageContent": null,
    "publicPageNotification": null,
    "notificationType": 0,
    "orderPickupInstructions": null,
    "productLines": [
        {
            "id": 1,
            "name": "Appliances",
            "sort": 0,
            "branches": null
        },
        {
            "id": 4,
            "name": "HVAC - Heating, Ventilation, and Air Conditioning",
            "sort": 0,
            "branches": null
        },
        {
            "id": 7,
            "name": "Plumbing",
            "sort": 0,
            "branches": null
        },
        {
            "id": 8,
            "name": "Pipes, Valves, & Fittings",
            "sort": 0,
            "branches": null
        },
        {
            "id": 9,
            "name": "Kitchen & Bath Showroom",
            "sort": 0,
            "branches": null
        },
        {
            "id": 11,
            "name": "Waterworks",
            "sort": 0,
            "branches": null
        }
    ],

CodePudding user response:

Your code says to print the data if the first item in the productLines array has ID 11. That is the productLines[0] bit. You need to search through each of the items in the productLines array and test each one for id === 11.

e.g.

for (i = 0; i < data.length; i  ) {
    for (j = 0; j < data[i].productLines.length; j  ) {
        if (data[i].productLines[j].id === 11) {
            console.log(data[i]);
        }
    }
}

Which is to say you have an array of arrays so you need two for, loops one for the outer array and one for the inner.

CodePudding user response:

Try this it will console if productLines have id 11, it should work for you.

for(i = 0; i < data.length; i  ) {
        for (j=0; j < data[i].productLines.length; j  ) {
            if (data[i].productLines[j].id === 11) {
                  console.log(data[i])
            }
      }
    }

if you need to get only those data in array of object which have at least one id with 11 in productLines you can try this it should work for you

 data.filter(item => (
    item.productLines.find(productItem => productItem.id === 11)
   ))

CodePudding user response:

A little more declaratively, this asks if a store has a particular productLine...

// define this at the top of the <script>
const storeHasProductLine = (store, productLineId) => {
  return store.productLines.find(line => line.id === productLineId);
}

Applying to the OP, filter the data (presumably, "stores") for those that satisfy the product line condition...

.then((data) => {
  const storesWithProductLine = data.filter(store => storeHasProductLine = (store, 11));
  console.log(storesWithProductLine);
})
  • Related