Reputation: 207
I have a json response in the form :
some_array = [{
ios: "110"
rate_pl: "PlanC"
ref_site: "N/A"
reservation_id: "12709034"
},{
ios: "121"
rate_pl: "SomePlan"
ref_site: "FB"
reservation_id: "1273034
},{
ios: "141"
rate_pl: "PlanC"
ref_site: "Tweet"
reservation_id: "143034
}];
How do i group a particular attribute say 'rate_pl' and also add the values if the ios which related to that particular rate_pl.
example --> Result should be:
someObject = [
{PlanC: ['ios':251]}, //(110+141 = 251)
{SomePlan: ['ios':121]}
];
Upvotes: 0
Views: 67
Reputation: 27976
The first thing to do is to group the array by rate_pl using _.groupBy:
var groups = _.groupBy(some_array,'rate_pl')
This will return an object with the keys being the distinct rate_pl values and the values will be an array of all the objects having that rate_pl:
{
PlanC: [ { ios: '110', etc }, {iod: '141' etc } ],
SomePlan: [ { ios: 121 etc } ]
}
The next thing to do is to transform the values into what you want (or something similar to what you want). This can be done using _.mapObject which was introduced in Underscore 1.8:
var result = _.mapObject(groups, function(rates){
return {
ios: _.reduce(rates, function(memo, rate){
return memo + parseInt(rate.ios);
}, 0)
}
});
This will give you:
{
PlanC: { ios: '251' },
SomePlan: { ios: 121 }
}
Upvotes: 1
Reputation: 157
As others have stated it is a bit confusing what you want since you are mixing arrays and objects.
Just to help you going, if you are looking for this response:
{
PlanC: {
ios: 251
},
SomePlan: {
ios: 121
}
}
You can use this code:
var new_object = {};
for (var i = 0; i < some_array.length; i++) {
if (angular.isUndefined(new_object[some_array[i].rate_pl])) {
new_object[some_array[i].rate_pl] = {ios: 0};
}
new_object[some_array[i].rate_pl].ios += parseInt(some_array[i].ios);
}
If you actually want some of the objects to be arrays that should be easy to modify.
Upvotes: 1
Reputation: 8110
You could use reduce function, like this:
var result = some_array.reduce(function(prev, cur) {
if (prev[cur.rate_pl] === undefined) {
prev[cur.rate_pl] = [];
prev[cur.rate_pl].push({ ios : parseInt(cur.ios, 10) });
} else {
prev[cur.rate_pl][0].ios += parseInt(cur.ios, 10);
}
return prev;
}, []);
Little demo.
Upvotes: 1