简体   繁体   中英

Iterating through an object array in js: skip when undefined

I'd like to iterate trough a javascript array (nested objects: based on collection+Json) and collect data from its objects. But if the data of an object isn't available, skip it and go to the next object, resp. continue the iteration. Currently, this error appears if the data isn't available in the according object: Uncaught TypeError: Cannot read property 'hk5' of undefined

How can I check first, if the data (hereafter hk5) is available?

Iterating through all "data-objects"

for (var i = 0; i < data.collection.items.length; i++) {
    var data = data.collection.items[i].data[2].value.packet_data_field.application_data_params.hk5;
    console.log(belaMode);
}

Thanks!

for (var i = 0; i < data.collection.items.length; i++) {
    if(typeof(data.collection.items[i].data[2].value.packet_data_field.application_data_params) != 'undefined'){
    var data = data.collection.items[i].data[2].value.packet_data_field.application_data_params.hk5;
    }
    console.log(belaMode);
}
if(data.collection.items[i].data[2].value.packet_data_field.application_data_params!=undefined){}

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