Как проверить, что массив объекта пуст? - PullRequest
0 голосов
/ 02 марта 2020

Я хочу проверить, является ли массив объектов пустым или нет, я сохраняю результат вызова API в состоянии 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)

Я получаю сообщение об ошибке double java.lang.Double.doubleValue() on a null object. даже попытался cities.length == 0 и (this.state.city_name).lenght == 0 он возвращает ту же ошибку.

Это данные из вызова API:

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"}]

Пожалуйста, помогите мне

Ответы [ 3 ]

2 голосов
/ 02 марта 2020

Проверьте длину массива и попробуйте выполнить свою задачу.

if(cities.length)
// do your task here
else
// handle here
1 голос
/ 02 марта 2020

Вы можете сделать что-то вроде этого

 cities = this.state.city_name;
 
 arr = cities.length;
 
 if(arr == 0) {
     console.log('no result found')
       }
 
 else {
     console.log(cities)
       }
0 голосов
/ 02 марта 2020

Я думаю, что проблема может быть в том, что вы используете ===, что строгое, и вы получите ошибку на двойном элементе. Null - это строка, а double - это число.

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