Skip to content
Advertisement

JavaScript add row level total property

I have the following javascript array:

[{ Year:2000, Jan:1, Feb: }, {Year:2001, Jan:-1, Feb:0.34 }]

I would like to add the total of Jan and Feb as a new property in the existing array.

Example:

[{ Year:2000, Jan:1, Feb:, Total: 1 }, {Year:2001, Jan:2, Feb:4, Total: -0.66 }]

How can I do this using JavaScript?

EDIT: Updated with decimal values

Advertisement

Answer

Assuming the empty value in Feb means 0 the following code will work.

var data = [{ Year:2000, Jan:1, Feb:0 }, {Year:2001, Jan:2, Feb:4 }];

data.forEach(item => {
    item.Total = item.Jan + item.Feb;
});


console.log(data); /* [
  { Year: 2000, Jan: 1, Feb: 0, Total: 1 },
  { Year: 2001, Jan: 2, Feb: 4, Total: 6 }
]*/


User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement