繁体   English   中英

Vue.js-如何按对象获取JSON数据?

[英]Vue.js - How to fetch JSON data object by object?

我有一个很大的JSON文件(40 MB),其中包含有关国家/地区,其ID和最后一个总计所需的总和的信息。

{
        "0": {
                "id": 0,
                "country": "usa",
                "sum": 201,
        },
        "1": {
                "id": 1,
                "country": "fr",
                "sum": 133,

        }
}

当我尝试将这些数据提取到一个变量中时,它可以很好地工作,但会占用大量内存,因此我想读取这些国家对象的“求和”字段,然后计算总和。 我怎样才能做到这一点?

我正在使用以下代码来获取整个JSON:

fetch(fetchURL)
    .then(response => response.json())
    .then(responseJSON => {
        this.json_data = responseJSON;
    })
    .catch(error => {
        console.log(error);
    });

responseJSON.sum不起作用,我认为它需要索引,但无法在获取中进行。

我不确定是否要完全理解要执行的操作:要么由于您的responseJSON太大而获得仅具有sum属性的数组,要么获得所有sum变量的实际总和。

这是一部分代码,可能会有所帮助:

var countries = [
 {
   "id": 0,
   "country": "usa",
   "sum": 201,
 },
 {
   "id": 1,
   "country": "fr",
   "sum": 133,
 }
];

var totalSum = 0;

var sumArray = countries.map(function(country) {
  totalSum = totalSum + country.sum;
  return country.sum;
});

在这部分代码中,我正在使用javascript map函数来获取其中包含所有sum变量的数组。 我也用totalSum变量sum变量的sum

如果您只需要获取sum变量的sum ,我宁愿建议使用forEach javascript函数而不是map函数。

希望这会有所帮助...

在ES6中,您可以简单地执行以下操作:

 fetch(fetchURL)
        .then(response => response.json())
        .then(responseJSON => {
            var sum = 0;
            for(var i = 0; i < Object.keys(responseJSON).length; i++) {
              sum += responseJSON[i]['sum'];
            }
            console.log(sum); // This is the total sum
        })
        .catch(error => {
            console.log(error);
        });

您可以简单地使用reduce函数来做到这一点,如下所示

 fetch(fetchURL)
    .then(response => response.json())
    .then(responseJSON => {
    const reducer = (accumulator, currentValue) => accumulator.sum + currentValue.sum;
        let sum =Object.values(responseJSON).reduce(reducer);

    })
    .catch(error => {
        console.log(error);
    });

 let arr = { "0": { "id": 0, "country": "usa", "sum": 201, }, "1": { "id": 1, "country": "fr", "sum": 133, } } const reducer = (accumulator, currentValue) => accumulator.sum + currentValue.sum; let sum = Object.values(arr).reduce(reducer); console.log(sum) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM