使用重复值中的唯一值过滤对象数组

时间:2015-10-12 14:39:08

标签: javascript arrays angularjs

var  Error-dictionary = [
   {
      code:599,
      MSG:'unknown' 
   },
   {
      code:404, 
      MSG:'not found'
   },
   {
      code:599, 
      MSG:'unknown'
   }
]

我想要这样的事情:

[
  {
     code : 599,
     count:2,  
     MSG : 'unknown', 
     code :404,
     count:1,
     MSG : 'not found' 
  }
] 

这需要推进 $scope.alerts作为MSG

错误代码和MSG是动态的

2 个答案:

答案 0 :(得分:1)

您可以使用underscore.js获取对象数组中特定属性的编号。好,易于!!!

<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>

答案 1 :(得分:0)

创建一个使用错误代码和消息作为键的临时对象。然后将该临时对象映射到输出数组

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);