How come I am getting only a single outcome when iterating through a dataset array?

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",
            ...
        }
    ],

Answer №1

Your code instructs to output the data only if the initial item in the productLines array has ID 11, which corresponds to productLines[0]. To achieve this, you must iterate through each item in the productLines array and check if its id is equal to 11.

For example:

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]);
        }
    }
}

This means that since you have an array of arrays, you will require two nested for loops - one for the outer array and another for the inner array.

Answer №2

Give this a shot - it will log the data if productLines has an id of 11. Give it a try.

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

If you only want the objects in the array that have at least one id with 11 in productLines, you can use this code:

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

Answer №3

In simpler terms, this code snippet checks if a store carries a specific productLine...

// Add this function at the beginning of your <script> tag
const checkStoreForProductLine = (store, productLineId) => {
  return store.productLines.find(line => line.id === productLineId);
}

In the context of the original poster (OP), it filters through the data (likely representing "stores") to find those that meet the product line requirement...

.then((data) => {
  const filteredStores = data.filter(store => checkStoreForProductLine(store, 11));
  console.log(filteredStores);
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to bypass the serialization and deserialization process for users in Passport.js?

Utilizing Passport.js and Angular for a web application, I aim to leverage Passport.js for authentication without the use of sessions. However, I consistently encounter an [Error: Failed to serialize user into session] each time I attempt to authorize a us ...

Tips for resetting/removing a Chart.js canvas in a React JSX element

I have encountered an issue with chart.js while working on a specific report. Whenever I switch pages to another page that includes chartjs elements and then switch back, the chart displays data labels on the data points like "x: number, y: number". Afte ...

Discover the steps to capture the ajax initiation and completion events

In my application, I have numerous ajax requests. To display a loading symbol while these requests are in progress, I am utilizing jquery ajaxStart and ajaxStop methods. However, for some reason, they seem to not be functioning as expected. Despite searc ...

Setting up the html div to contain the three.js container

Within my article container, there are three aside tags. The third aside with id='menuPuzzleType' contains a Three.js script that creates and displays two cube meshes in a Canvas renderer. <article id="popup"> <aside id='close ...

Encountering problems with assigning elements using TYPE syntax

I'm struggling to correctly implement TYPE for a generic array. While I can make the code work with int, I encounter issues with TYPE when trying to assign values. Here's how I create the array: struct DynArr { TYPE *data; /* pointer to ...

Converting an array into an object using Typescript and Angular

I have a service that connects to a backend API and receives data in the form of comma-separated lines of text. These lines represent attributes in a TypeScript class I've defined called TopTalker: export class TopTalker { constructor( pu ...

The path is visible, yet the ajax call does not make it through - it's simply "off course"

rake routes is used to verify the existence of a route: control1_route1 DELETE /control1/route1(.:format) However, when attempting to make a "delete" request to this route: var url = "<%= control1_route1_url %>"; $.ajax({url: url, type: "D ...

Serialization not being successful

Having an issue with my form that is being loaded and posted using ajax. When trying to send the data, nothing is added to the post. Here's a simplified version of the code: <form id="userForm"> <input type="text" name="username" /> ...

Utilizing arrays in Expressjs: Best practices for passing and utilizing client-side arrays

Here is the structure of an object I am dealing with: editinvite: { _id: '', title: '', codes_list: [] } The issue I am facing is that I am unable to access the codes_list property in my NodeJS application. It appears as 'u ...

React Redux fails to dispatch an action

Recently, I attempted to integrate Redux into my React application. I created a container called SignIn that instantiates a mapDispatchToProps and connects it to the component. The SignIn component renders a sub-component called SignInForm (code provided ...

Is the reordering of items in an Angular JS array causing a malfunction with the first item

It appears that there may be a syntax error present in my code. Within my controller, I have a set of 4 functions: adding a new item, deleting the current item, moving an item backward (up) in the array, and moving an item forward (down) in the array. Al ...

Having trouble establishing a connection from regular JavaScript to a socket.io backend? Face the issue of connection closure before

As I attempt to link my client-side JavaScript with a backend websocket service utilizing socket.io, I encounter an issue. I am attempting to establish a connection to the socket.io server using the native WebSocket object: new WebSocket("wss://localhost ...

Create unique names by merging a selection of words

I'm looking to create a feature where users can input 2 or 3 words into text fields, and upon submission, those words will be combined in various ways. It's similar to a business name generator where you enter words and receive potential business ...

Is it possible to implement JSON formatting by pushing a named Array into an existing Array for each set?

Struggling with a JSON API issue involving multiple result sets from the database. My aim is to have a named array, "card" for each row returned. This is how I want the JSON to be formatted: { "results": [ { "card": { ...

Node.js is essential when using Angular for implementing ui-select components

I'm currently delving into learning AngularJS. I've successfully created a basic web application using AngularJS, with Java EE powering the backend (server side). This app is being hosted on Tomcat. The advantages of AngularJS over JQuery are bec ...

prevent unauthorized changes to input using browser developer tools in Angular

We have a login page for our application with three fields: "user name," "password," and a "login" button. Here's the issue I'm facing: I enter a valid user name. Then, I open the Browser Developer Tools and input the following code: d ...

What is the best method to delete an attribute from an element using Angular?

When working with Angular, how can I remove an attribute or its value? For example, say I have an ng-click event that I only want to fire once. One approach could be to create a 'self-destruct' in the ng-click event like this: elementClicked = f ...

Extracting data from a JSON file and storing it into a variable, then retrieving a specific value from that variable and assigning it

When it comes to handling JSON data, I'm doing more than just parsing it. I'm actually using cURL to hit a URL and retrieve the JSON response that I want to store in a variable. Here's an example of the JSON format I'm working with: [ ...

Execute a jQuery function every time the class of the parent container div changes

I am seeking to trigger the function below whenever its containing div parent <div class="section">...</div> transitions to an "active" state, for example: <div class="section active">...</div> $(".skills-grid__col").each(function ...

The requested resource does not have the 'Access-Control-Allow-Origin' header, resulting in a 401 error

I've been working on integrating spell check functionality using the Bing Spell Check API, but I've run into a 401 error. The specific error message is: The requested resource does not have an 'Access-Control-Allow-Origin' header. This ...