简体   繁体   中英

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.

Use loop control :

for (var i in obj) {
   if (obj[i].length == 0) {
       continue;
   }
   ...
}

You need to pass the key to delete a property :

for ( var i in obj ){
    if ( obj[i].length == 0 ) {
        delete i
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM