Sam
Sam

Reputation: 548

How to loop through each entry in using For Loop JavaScript

My loop function is as below

 var resources= jsonObj.entry;
 var resourceType;
 var i;
 for (i = 0; i < resources.length; i++) {
  resourceType += resources[i];
  }

  console.log(resourceType)

if i do jsonObj.entry[0] i get the first entry so i implemented for-loop to get all the entries but console.log on resourceType prints the following

Console log result

jsonObj.entry

Upvotes: 0

Views: 80

Answers (1)

rmjoia
rmjoia

Reputation: 980

So, one way to do it is

var resources = jsonObj.entry;
var resourceTypeArray = [];
var resourceType = "";

for (let item = 0; item <= resources.length; item++) {
  // This will remove all cases where the item doesn't exist and/or resource doesn't exist
  if(resources[item] && resources[item].resource){
      resourceTypeArray.push(resources[item].resource);  
      resourceType += JSON.stringify(resources[item].resource);
  }
}

// printing out to the console the array with resources
console.info(resourceTypeArray);

// printing out to the console the string with the concatenation of the resources
console.info(resourceType);

I also created a StackBlitz with the working solution and your json file kindly provided.

hope it helps.

Upvotes: 1

Related Questions