Looping through json | Sololearn: Learn to code for FREE!

+2

Looping through json

Hi guys assume you have a json object like this { meal:beans, Image:pexels.com Health :true ingredient1:onions, ingredient2:potatoes, ingredient3:beans, } How do you loop through to console.log all your ingredients, assuming your object has 25 ingredients

5/23/2020 5:19:42 PM

John Bryan

4 Answers

New Answer

+8

for ( var key in myJSON){ if ( key.indexOf("ingredient") == 0){ console.log(myJSON[key]); } }

+4

The for...in loop is intended for iterating over the enumerable keys of an object. https://www.sololearn.com/learn/JavaScript/2970/?ref=app That's how it moves to the next object key. This iterates over ALL enumerable keys but we only want to log the "ingredients". indexOf is a string method that returns the index where a given string is located in the string that called the method. -1 is returned when the substring is not found. E.g: "abcdef".indexOf ("b") == 1; //true "abcdef".indexOf ("bcdef") == 1; //true "abcdef".indexOf ("fgh") == -1; //true The if statement could be read this way: if (the key has "ingredient" as a substring [from index 0] ) Then console.log(myJSON [key] ) to get the value. or if (the key starts with "ingredient") Then log the value. In ES6 and above the if statement is easier to write and read : if(key.startsWith("ingredient"){ console.log(myJSON [key]) } John Bryan You are very welcome.

+1

Got it Thanks Kevin Star

0

This worked But could you please explain the if statement Isn't the 0 supposed to increment(++) or how does it move to the next ingredient