Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I skip key in object loop

I was wondering if there is any way to skip key in object loop. If I have:

obj = {
   key1 : [ 1, 2, 3 ],
   key2 : [ 4, 5 ],
   key3 : []
}

how can I skip, for example, the empty one. Because I want to join() the not empty arrays in that object, and filter them. If I join that empty array the filter looks for empty string and of course it doesn't find it, and everything brakes.

var match = $('.widget');
for ( var i in obj ){
    var joined = obj[i].join();
    match = match.filter(joined);
}

I have tried to delete it:

if ( obj[i].length == 0 ) {
    delete obj[i]
};

but error occurs that obj[i] is undefined and can't join it. How can I just skip it.

like image 311
Панайот Толев Avatar asked Dec 17 '25 03:12

Панайот Толев


2 Answers

Use loop control:

for (var i in obj) {
   if (obj[i].length == 0) {
       continue;
   }
   ...
}
like image 51
Marc B Avatar answered Dec 19 '25 19:12

Marc B


You need to pass the key to delete a property :

for ( var i in obj ){
    if ( obj[i].length == 0 ) {
        delete i
    }
}
like image 44
Denys Séguret Avatar answered Dec 19 '25 20:12

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!