< Back to Coding, jQuery

Looping through an object with forEach

With example data like this:

var data = {
      "animals": [
          {
              "name": "cat",
              "legs": 4
          },
          {
              "name": "bird",
              "legs":2
          }
      ]
  };
Object.keys(data.animals).forEach(function(index) {
        if(data.animals[index].legs === 2){
          console.log(data.animals[index].name);
        }
      });

which console logs “bird”

Leave a Reply

Your email address will not be published. Required fields are marked *