Aggregate and transform array of objects

时间:2016-02-03 04:21:24

标签: javascript arrays dictionary functional-programming map-function

Using javascript functional programming methods (like map/reduce), how would one aggregate/count the status field of arr1 and transform it to an array of key/value objects in arr2.

arr1 = [
  {'task':'do something 1', 'status':'done'} , 
  {'task':'do something 2', 'status':'done'} , 
  {'task':'do something 3', 'status':'pending'} , 
  {'task':'do something 4', 'status':'done'}
];

// Aggregate arr1 `status` field and transform to:

arr2 = [
  {key:'done', value: 3},
  {key:'pending', value: 1}
];

Here's my WIP partial solution that handles only the aggregation portion. I still need the transform portion.

var arr2 = arr1.map(function(item) {
    return item.status;
  }).reduce(function(acc,curr,idx){
    if(acc[curr] === undefined) acc[curr] = 1;
    else acc[curr] += 1;
    return acc;
  }, []); 

3 个答案:

答案 0 :(得分:0)

您可以尝试Array.prototype.forEach()。而不是使用数组,您可以使用对象。这将节省您循环以查找特定状态的计数。



arr1 = [
  {'task':'do something 1', 'status':'done'} , 
  {'task':'do something 2', 'status':'done'} , 
  {'task':'do something 3', 'status':'pending'} , 
  {'task':'do something 4', 'status':'done'}
];

var result = {};
arr1.forEach(function(item){
  if(!result[item.status])
    result[item.status] = 0;
  
  result[item.status]++;
});
console.log(result);




答案 1 :(得分:0)

这是我能想到的最实用的方式。这包括聚合和您想要的转换:

var arr2 = Object.keys(arr2 = arr1.map(function(item) {
    return item.status;
}).reduce(function(acc,curr){
    acc[curr] = acc[curr] + 1 || 1;
    return acc;
}, [])).map(function(item){
    return {key: item, value: arr2[item]}
});

答案 2 :(得分:0)

由于您将输出值存储为数组,因此应检查天气是否存在键状态。如果存在则增加其值。

arr2 = [];
arr1.forEach(function(item){
  var keyPresent = false;
  for(var i = 0, len = arr2.length; i < len; i++) {
      if( arr2[ i ].key === item.status ){
         keyPresent = true;
         arr2[ i ].value++
      }
  }
  if(!keyPresent){
    arr2.push({key: item.status , value : 1})
}

给出的输出
arr2 = [
  {key:'done', value: 3},
  {key:'pending', value: 1}
];