Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the length of JSON response in React Native/JS?

Tags:

javascript

I would like to count the length of my response JSON. Here's my code:

getMoviesFromApiAsync() {
return fetch('http://sampleurl.com/' + CommonDataManager.getInstance().getUserID())
    .then((response) => response.json())
    .then((responseJson) => {
        this.setState({isLoading: false, listMessages: responseJson});    
    })
    .catch((error) => {
        console.error(error);
    });
}
like image 239
Deee Avatar asked Sep 03 '17 07:09

Deee


1 Answers

Count the keys

  var myObject = {'key':'something', 'other-key':'something else','another-key': 'another thing'}
  var count = Object.keys(myObject).length;

Where myObject is your json response and count is the length of your object

This is the best way to count the json objects correctly

In your code you should add this in your second .then

var count = Object.keys(responseJson).length;
like image 187
Joe Lloyd Avatar answered Sep 28 '22 08:09

Joe Lloyd