javascript 如何计算 React Native/JS 中 JSON 响应的长度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46021238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:23:14  来源:igfitidea点击:

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

javascript

提问by Deee

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

我想计算我的响应 JSON 的长度。这是我的代码:

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);
    });
}

回答by Joe Lloyd

Count the keys

数钥匙

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

Where myObjectis your json response and countis the length of your object

myObject你的 json 响应在哪里,是你count的对象的长度

This is the best way to count the json objects correctly

这是正确计算 json 对象的最佳方法

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

在您的代码中,您应该在第二个中添加它 .then

var count = Object.keys(responseJson).length;