Search code examples
javascriptarraysloopsobjectiterator

Iterate through array of objects using javascript


I am trying to iterate through the array of objects but somehow not getting it right. Can somone please let me know where i am going wrong.

Here is the data

const response = {
    "pass": 1,
    "fail": 2,
    "projects_all": [
        {
            "projects": [
                {
                    "name": "Project1",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "UNKNOWN",
                    }
                }
            ]
        },
        {
            "projects": [
                {
                    "name": "Project2",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "FAIL",
                    }
                },
                {
                    "name": "Project3",
                    "status": "LIVE",
                    "current": null,
                    "previous": {
                        "environment": "qa4nc",
                        "status": "UNKNOWN",
                    }
                }
            ]
        }
    ]
}

And here is the code i tried

if(response) {
  response?.projects_all?.forEach((projects) => {
     projects.forEach(project) => {
       if(project.previous !== null) {
         //do something here
       }
    });
 });
}

I am trying to iterate through this array of objects but it says projects not iterable. Any help is appreciated to make me understand where i am going wrong.


Solution

  • You were missing iterating over an array properly. A good idea is to format the JSON object that you plan to iterate over. So that you can see what are the arrays and objects, and at what hierarchy.

    if (response) {
      response?.projects_all?.forEach((project) => {
        project?.projects?.forEach((project) => {
          console.log(project?.name);
        });
      }
      );
    }