GeekyMoktan
GeekyMoktan

Reputation: 11

How to loop through array inside of Object?

const obj = {
  "urls": [{
      "url": "youtube.com",
      "category": ["react js", "javascript"]
    },
    {
      "url": "facebook.com",
      "category": ["react js", "javascript"]
    }
  ]
}

const loop = (a) => {
  for (let j = 0; j < a.length; j++) {
    console.log(a[j].url);
  }
  return;
}

for (let i in obj) {
  console.log(i + " " + loop(obj[i]));
}

The output is:

"youtube.com"
"facebook.com"
"urls undefined"

Why does the loop function get executed first? It should only run inside the second loop:

for(let i in obj){
console.log(i + " " + loop(obj[i])  );
}

I want to be able to output:

urls : youtube.com reactjs,javascript

Upvotes: 1

Views: 51

Answers (1)

Nick is tired
Nick is tired

Reputation: 7056

With short code often the easiest thing to do to debug it is to just do a basic walkthrough of your code by hand to see if it's really doing what you want it to.

You'll notice that the second loop simply performs:

console.log("urls" + " " + loop(obj["urls"])  );

This will result in loop being called:

console.log(obj["urls"][0].url);
console.log(obj["urls"][1].url);
return; // returns undefined

Which will output:

youtube.com
facebook.com

Only then (after the first two logs from inside the loop call) will the initial console.log take place with the return value of loop:

console.log("urls" + " " + undefined /*loop(obj["urls"])*/  );

Giving your last line of output:

urls undefined

As for why loop gets called before the console.log("urls" + ...), think about it, how can console.log know what to output, if to output it it needs to have called loop? loop has to come first.


It sounds like you were trying to do something like this:

const obj = {
  "urls": [{
      "url": "youtube.com",
      "category": ["react js", "javascript"]
    },
    {
      "url": "facebook.com",
      "category": ["react js", "javascript"]
    }
  ]
}

// Constructs a string representation of the list of categories
const loop = (a) => {
  o = "";
  for (let j = 0; j < a.category.length; j++) {
    o += "," + a.category[j];
  }
  return o.substring(1);
}

// Call loop for each url in obj
for (let i in obj.urls) {
  console.log("urls : " + obj.urls[i].url + " " + loop(obj.urls[i]));
}

This can be tidied up using join instead of your loop function and by using Array.prototype.forEach:

const obj = {
  "urls": [{
      "url": "youtube.com",
      "category": ["react js", "javascript"]
    },
    {
      "url": "facebook.com",
      "category": ["react js", "javascript"]
    }
  ]
}

// Call loop for each url in obj
obj.urls.forEach(urlObj => {
    console.log("urls : " + urlObj.url + " " + urlObj.category.join(","));
});

Upvotes: 1

Related Questions