0

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

13
  • 1
    Check out What is the difference between ( for… in ) and ( for… of ) statements in JavaScript? and.. aren't you forgetting to use the index on your code snippet there? Commented Feb 18, 2020 at 10:31
  • 1
    along with missing index like resorces[i] you should initialize resourceType with an empty string, like resourceType = "". Commented Feb 18, 2020 at 10:33
  • Are you wanting to change [object Object] or get rid of the undefined at the start? Commented Feb 18, 2020 at 10:34
  • @sam is this what you're trying to achive? example Commented Feb 18, 2020 at 10:36
  • You seem to be concatenating objects. (Doing something like {}.toString() + {}.toString()) Is this what you want? Commented Feb 18, 2020 at 10:36

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.