I am trying to create a new object from looping through the below and combining values of objects that have like types?
so I have something like this:
var data = [{
transID: 123,
repId: 86,
profit: 117.3,
expense: 96.76 },
{
transID: 124,
repId: 35,
profit: 47.39,
expense: 15.15 },
{
transID: 125,
repId: 86,
profit: 62.62,
expense: 15.17 }]
So i need to create a new array same as above, only for each rep I want one object with a sum of the profit and expense like (so no transID either):
[{
repId: 86,
profit: 179.92,
expense: 111.93 },
{
repId: 35,
profit: 47.39,
expense: 15.15 }]
i am just learning (go easy this may be totally wrong) but I have tried things like:
var otherData = [];
for ( var i = 0; i < data.length; i++ ) {
var thisDataObj = data[i];
for ( var j = 0; j < data.length; i++) {
var thisComparedData = data[j]; // maybe a ridiculous approach ??
if(thisDataObj.repId == thisComparedData.repId) {
if(thisDataOjb.transId != thisComparedData.transId) {
// struggling with this part if this is event the right approach
// the loop is bad because it will recount
}
}
}
so without showing the things i tried within that loop, i am pretty sure this is just wrong as it will recount values if I tried to sum, create the object and push it. just not sure what is a better way?
any help is greatly appreciated.
just not sure what is a better way?
Yes, you can use an object as a lookup map for new objects by repId:
var map = {};
for (var i=0; i<data.length; i++) {
var obj = data[i],
id = obj.repId;
if (id in map) { // we know this id already
// get the object and sum properties
map[id].profit += obj.profit;
map[id].expense += obj.expense;
} else // create a new one
map[id] = {
repId: id,
profit: obj.profit,
expense: obj.profit
};
}
/* map:
{
"35":{"repId":35,"profit":47.39,"expense":47.39},
"86":{"repId":86,"profit":179.92,"expense":132.47}
} */
// put the values from the map in an array
var otherData = [];
for (var id in map)
otherData.push(map[id]);
/* otherData:
[
{"repId":35,"profit":47.39,"expense":47.39},
{"repId":86,"profit":179.92,"expense":132.47}
] */