Hello, I have an object containing several sub-objects. I was wondering if there is a way to loop through the subobjects starting from the wrapper object grid, all the way down to the deepest subobjects using a for in loop. var grid = { A:{a:{shots:[],ennemies:[]},b:{shots:[],ennemies:[]},c:{shots:[],ennemies:[]},d:{shots:[],ennemies:[]},e:{shots:[],ennemies:[]},f:{shots:[],ennemies:[]},g:{shots:[],ennemies:[]}}, B:{a:{shots:[],ennemies:[]},b:{shots:[],ennemies:[]},c:{shots:[],ennemies:[]},d:{shots:[],ennemies:[]},e:{shots:[],ennemies:[]},f:{shots:[],ennemies:[]},g:{shots:[],ennemies:[]}}, C:{a:{shots:[],ennemies:[]},b:{shots:[],ennemies:[]},c:{shots:[],ennemies:[]},d:{shots:[],ennemies:[]},e:{shots:[],ennemies:[]},f:{shots:[],ennemies:[]},g:{shots:[],ennemies:[]}}, D:{a:{shots:[],ennemies:[]},b:{shots:[],ennemies:[]},c:{shots:[],ennemies:[]},d:{shots:[],ennemies:[]},e:{shots:[],ennemies:[]},f:{shots:[],ennemies:[]},g:{shots:[],ennemies:[]}}, E:{a:{shots:[],ennemies:[]},b:{shots:[],ennemies:[]},c:{shots:[],ennemies:[]},d:{shots:[],ennemies:[]},e:{shots:[],ennemies:[]},f:{shots:[],ennemies:[]},g:{shots:[],ennemies:[]}}, F:{a:{shots:[],ennemies:[]},b:{shots:[],ennemies:[]},c:{shots:[],ennemies:[]},d:{shots:[],ennemies:[]},e:{shots:[],ennemies:[]},f:{shots:[],ennemies:[]},g:{shots:[],ennemies:[]}}, G:{a:{shots:[],ennemies:[]},b:{shots:[],ennemies:[]},c:{shots:[],ennemies:[]},d:{shots:[],ennemies:[]},e:{shots:[],ennemies:[]},f:{shots:[],ennemies:[]},g:{shots:[],ennemies:[]}}, } I’d like to check wether the shots and ennemies arrays contain sth. To do that I am currently using a long series of if/else if for each of the 49 possibilities : if if(grid.A.a.shots.length>0&&grid.A.a.ennemies.length>0), else if(grid.A.b.shots.length>0&&grid.A.b.ennemies.length>0),etc. I am already using this : for (var prop in obj){ console.log(obj[prop]) } which returns only first depth of the grid object.
Hi WillyFR. sth ? Anyways, I could do something like below using your grid var: var totalShots = 0, totalEnnemies = 0; for(var i in grid){ var subgrid = grid[i]; for(var j in subgrid){ totalShots += subgrid[j].shots.length; totalEnnemies += subgrid[j].ennemies.length; } } console.log('totalShots: ', totalShots); console.log('totalEnnemies: ', totalEnnemies); Code (JavaScript): But perhaps you'd enjoy many of built-in array features / functions though, if that grid were structured like: var grid = [{ name: 'A', subgrid:[{ name:'a', shots:[], ennemies:[] },{ name:'b', shots:[], ennemies:[] },{ ... }] },{ name: 'B', subgrid:[{ name:'a', shots:[], ennemies:[] },{ name:'b', shots:[], ennemies:[] },{ .... }] },{ ... }]; Code (JavaScript): No?