6

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);
    });
}
2
  • 2
    Please read Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers? - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. Commented Sep 3, 2017 at 8:19
  • 2
    You are welcome. The community also prefers titles written in natural English. Grammatically, "React How to count the length of a JSON response" doesn't make a lot of sense (though I understand the purpose of using "ReactJS" as a home-made tag). However, since we have a tagging system, it is better to merge the "tag" into the question, or get rid of it completely, since it is already in the tag list. Commented Sep 3, 2017 at 8:37

1 Answer 1

16

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;
Sign up to request clarification or add additional context in comments.

3 Comments

which part in my code should I replace myObject variable?.
Hi sir Joe can I call the count variable outside my function? or maybe to another file?.
thats an issue. you can declare it outside, but this is asynchronous and might not always be the expected value. I would suggest that if you need to use the value count for something you call that in the .then statement to ensure it exists. This is the entire point of a promise

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.