js nested loops arrays and objects

by Ken Sprague

JavaScript

//nested loops and multi-dimensional objects
//we can use nested loops to access all the elements
//inside multi-dimensional arrays or objects


let twoD = [[1, 2, 3, 4, 5, 6, 7],
					 [8, 10, 5, 7, 3, 22, 6, 42],
           [123, 54, 12, 11, 9, 15]];
           
let bigHero = {characters:[
								{name:'Batman', id:'Bruce Wayne'},
                {name:'Robin', id:'Damian Wayne'},
                {name:'Flash', id:'Barry Allen'},
                {name:'Spiderman', id:'Peter Parker'},
						]};           
            
//nested for loops
/*let rows = twoD.length;
for(let i = 0; i < rows; i++){
		let items = twoD[i].length;
    console.log(i, items);
    for(let n = 0; n < items; n++){
    		//to get inside values of nested array
        console.log( twoD[i][n] );
    }
}*/

let chars = bigHero['characters'];// or use bigHero.characters
for(let i = 0, len=chars.length; i<len; i++){
//		console.log(chars[i]);
//    console.log(chars[i].name);
//    console.log(chars[i]['id']);
  	for(let prop in chars[i]){  
//becasue it's a string we have to use the square brackets
    	console.log(prop, chars[i][prop]);
	}
}