简体   繁体   中英

How to check if array of object is empty?

I want to check if the array of objects is empty or not, I'm storing the result from API call in state city_name .

cities = this.state.city_name;
console.warn(cities); //this return an empty array []
cities === null ? console.log(cities) : ToastAndroid.showWithGravity('No Result 
                                                                      Found',ToastAndroid.LONG)

I keep getting an error double java.lang.Double.doubleValue() on a null object . even tried cities.length == 0 and (this.state.city_name).lenght == 0 it return the same error.

This is the data from API call:

city_name = [{"country_flag_url": "https://b.zmtcdn.com/images/countries/flags/country_216.png", "country_id": 216, "country_name": "United States", "discovery_enabled": 1, "has_go_out_tab": 0, "has_new_ad_format": 0, "id": 11282, "is_state": 0, "name": "Del Aire, CA", "should_experiment_with": 0, "state_code": "CA", "state_id": 73, "state_name": "California"}, {"country_flag_url": "https://b.zmtcdn.com/images/countries/flags/country_216.png", "country_id": 216, "country_name": "United States", "discovery_enabled": 0, "has_go_out_tab": 0, "has_new_ad_format": 0, "id": 4463, "is_state": 0, "name": "Del Norte, CO", "should_experiment_with": 0, "state_code": "CO", "state_id": 74, "state_name": "Colorado"}, {"country_flag_url": "https://b.zmtcdn.com/images/countries/flags/country_216.png", "country_id": 216, "country_name": "United States", "discovery_enabled": 0, "has_go_out_tab": 0, "has_new_ad_format": 0, "id": 9431, "is_state": 0, "name": "Del Rio, TX", "should_experiment_with": 0, "state_code": "TX", "state_id": 111, "state_name": "Texas"}]

Please help me

Check for the length of the array and then try to do your task.

if(cities.length)
// do your task here
else
// handle here

You can do something like this

 cities = this.state.city_name; arr = cities.length; if(arr == 0) { console.log('no result found') } else { console.log(cities) }

I think the issue may be that you are using === which is strict and you will get the error on a double element. Null is a string and double is a number.

if(cities != null && cities.length>0){
    //not empty, do something with data
}else
    //array is empty, so add values.

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