Reputation: 105
var Error-dictionary = [
{
code:599,
MSG:'unknown'
},
{
code:404,
MSG:'not found'
},
{
code:599,
MSG:'unknown'
}
]
I want something like this:
[
{
code : 599,
count:2,
MSG : 'unknown',
code :404,
count:1,
MSG : 'not found'
}
]
and this need to push into
$scope.alerts
as a MSG
Error code and MSG are dynamic
Upvotes: 1
Views: 92
Reputation: 10992
You can get the number of an specific property in a array of objects, by using underscore.js. Nice and easy!!!
<script src="http://underscorejs.org/underscore-min.js"></script>
<script>
window.onload = function () {
var dict = [
{code: 599, MSG: 'unknown' },
{code: 404, MSG: 'not found'},
{code: 599, MSG: 'unknown'}
];
var res = _.groupBy(dict, function (d) {
return d.code;
});
var dictArr = [];
for(var key in res) {
var code = key;
var value = res[key];
var MSG = value[0].MSG;
var count = value.length;
dictArr.push({ code : code, MSG: MSG, count: count });
};
console.log(dictArr);
};
</script>
Upvotes: 1
Reputation: 171679
Create a temp object that uses the error code and message as keys. Then map that temp object to output array
var tmp = {}, res =[];
data.forEach(function (item) {
var tmpKey = item.code + item.MSG;
if (!tmp.hasOwnProperty(tmpKey)) {
tmp[tmpKey] = angular.copy(item);
tmp[tmpKey].count = 0;
}
tmp[tmpKey].count++;
});
for( var key in tmp){
res.push(tmp[key];
}
$scope.errors = res;
console.log($scope.errors);
Upvotes: 0