Sum values of a specific property in javascript object

12,717

Solution 1

highlights is an array and you should be looping over that.

var highlights = [
  {properties : { census2010_Pop2010: 10}},
  {properties : { census2010_Pop2010: 20}},
  {properties : { census2010_Pop2010: 30}}
]

var total = highlights.reduce( function(tot, record) {
    return tot + record.properties.census2010_Pop2010;
},0);


console.log(total);

If you want to use forEach it would be like this:

var highlights = [
  {properties : { census2010_Pop2010: 10}},
  {properties : { census2010_Pop2010: 20}},
  {properties : { census2010_Pop2010: 30}}
]

var total = 0;
highlights.forEach( function(record) {
    total += record.properties.census2010_Pop2010;
});


console.log(total);

Solution 2

This can be achieved by using reduce to total the value of census2010_Pop2010:

const total = highlights.reduce((acc, val) => acc + val.properties.census2010_Pop2010, 0);

Note: I have used the ES6 arrow function to keep it concise, this is not necessary but, becoming more common when adopting a more functional style with methods like map, filter and reduce.

Solution 3

total = 0;

highlights.forEach(function(a) {
    total += Number(a.Feature.properties.census2010_Pop2010);
})
console.log(total);

You need to loop through each of the "Feature" objects in the "highlights" array. You start with a total of 0, then incrementally add the census2010_Pop2010 values from each Feature.

Share:
12,717
the_darkside
Author by

the_darkside

Updated on June 23, 2022

Comments

  • the_darkside
    the_darkside almost 2 years

    On a click event in my application I am returned highlights - an array of features (each time of differing length). So console.log(highlights) produces:

    enter image description here

    My objective is to return the sum of the values contained in properties.census2010_Pop2010 for each feature in the object. So far I have tried the code below but nothing is returned in the console. Any suggestions would be appreciated.

    total = Object.create(null);
    
    highlights.feature.properties.forEach(function (a) {
        a.census2010_Pop2010.forEach(function (b) {
            total = total + b.census2010_Pop2010;
        });
    });
    
    console.log(total);
    
  • milo526
    milo526 almost 7 years
    Welcome to Stack Overflow! While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
  • Chris Rouffer
    Chris Rouffer almost 7 years
    Thanks milo526. I've updated my answer to include an explanation