Reputation: 363
I have a big JSON file (40 MB) that contains information about countries, their ids and finally a sum that I need to get its total.
{
"0": {
"id": 0,
"country": "usa",
"sum": 201,
},
"1": {
"id": 1,
"country": "fr",
"sum": 133,
}
}
When I try to fetch this data into a variable it works good but consumes so much memory, so I want to read these country objects' only sum field and then calculate the total sum. How can I do that?
I'm using following code to get the whole JSON:
fetch(fetchURL)
.then(response => response.json())
.then(responseJSON => {
this.json_data = responseJSON;
})
.catch(error => {
console.log(error);
});
responseJSON.sum
does not work, I think it requires index but I couldn't do it in the fetch.
Upvotes: 1
Views: 2395
Reputation: 341
In ES6, you can simply do the following:
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);
});
Upvotes: 1
Reputation: 1
You could do it simply using reduce
function as follows
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);
});
Example
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)
Upvotes: 1
Reputation: 55
I am not sure to fully understand what you want to do: either get an array with only the sum
property because your responseJSON
is too big, or get the actual sum of all the sum
variables.
Here is a portion of code that might help :
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;
});
In this portion of code, I am using the javascript map function to get an array with all the sum
variables in it. I am also making the total sum of the sum
variables with the totalSum
variable.
If you just need to get the total sum of the sum
variables, I would rather recommend to use the forEach
javascript function rather than the map
function.
Hope this might help...
Upvotes: 2