How to access this JSON multidimensional

Hi, i would like to ask for a little help in JSon. my functions doesnt work. Thank you this will be a big help for someone newbie in JS

var info = {
        "gadgets": 
        	{
        	"phone" : 
        		[ 
		            {"product" : "QPhone 10","manufacturer" : "Apple","releaseDate" : "2029","price" : 600}, 
		            {"product" : "Gala SZ","manufacturer" : "Samsung","releaseDate" : "2018","price" : 350}, 
		            {"product" : "Xeria Z2","manufacturer" : "Sony","releaseDate" : "2020","price" : 399} 
          		],

          	"laptop" : 
          		[ 
            		{"product" : "NiceBook BRO 2018","manufacturer" : "Mango","releaseDate" : "2017","price" : 1999}, 
            		{"product" : "Vaio", "manufacturer" : "Ericson","releaseDate" : "2020","price" : 1690} 
          		]
        	}
      };


myFunction(info);

function myFunction(arr) {
      var out = "";
      var i;
      for(i = 0; i < arr.length; i++) {
          out += '<div class="prod-info"><div class="product large-font">' + arr[i].product + '</div>' + '<span class="prod-content small-font"> Manufactured by ' + arr[i].manufacturer  + ', to be released in ' +  arr[i].releaseDate + '</span>' + '<div class="price mid-font"> $' + arr[i].price + '</div></div>' + '<br>';
      }
      document.getElementById("content").innerHTML = out;
  }

The JSON you are passing in to myFunction does not have a length property so the for loop will never run.

Try this to get started:

Object.keys(obj).forEach(function(key,index) {
    // key: the name of the object key
    // index: the ordinal position of the key within the object 
});

More info: http://stackoverflow.com/questions/8312459/iterate-through-object-properties

If you just want to list all phones or all laptops, you could just pass either array to your function:
myFunction(info.gadgets.phone); // or myFunction(info.gadgets.laptop);

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.