I have stumbled upon a case I have never had before. I have an array of arrays and each array has several objects inside or nothing inside.
I use the objects to generate some HTML and all works well except when I try to handle the empty data (an array that has no objects inside). I was thinking to loop through them and if I get an array that is empty to create specific HTML but I just can't seem to handle it... maybe it sounds confusing when I explain like this, so I will leave the code snippet talk for itself
const theGrandArray = [
[
{id:1},
{id:12},
{id:13}
],
[
{id:2},
{id:22},
{id:23}
],
[], // this is the array I want to handle
[
{id:4},
{id:42},
{id:43}
]
]
const theUl = document.getElementById('theUl')
for(let i = 0; i < theGrandArray.length; i++ ){
for(let k = 0; k < theGrandArray[i].length; k++){
if(!theGrandArray[i][k].id){
console.log('ahaaa!')
}
let liElement = document.createElement('li')
liElement.innerText = theGrandArray[i][k].id
theUl.appendChild(liElement)
}
}
<ul id="theUl"></ul>
0do one thing, of> 0do what you're doing now (or whatever it is you need to do).k < theGrandArray[i].lengthis always false with the empty array.theGrandArray[i].lengthis0and0 < 0is false.forEachloop might help you see more clearly and debug accordingly