如何基于下划线js中的键和值对进行分组

时间:2016-05-30 15:53:16

标签: javascript underscore.js

我试图弄清楚如何使用下划线js对此数组进行分组。请帮我解决这个问题。

var result = [
    { phone_number: '777', type: 'ORDER_SMS' }, 
    { phone_number: '777', type: 'ORDER_CALL' },
    { phone_number: '999', type: 'ORDER_SMS' } 
];

//expected output
var result = [
    {'ORDER_SMS' : '777, 999'}, 
    {'ORDER_CALL': '777' }
];

2 个答案:

答案 0 :(得分:1)

1.使用下划线

var list = [{
    phone_number: '777',
    type: 'ORDER_SMS'
}, {
    phone_number: '777',
    type: 'ORDER_CALL'
}, {
    phone_number: '999',
    type: 'ORDER_SMS'
}];
var result = _.chain(list)
    .groupBy('type')
    .map(function(value, key) {
        // console.log(value)
        return {
            type: key,
            phone_numbers: _.pluck(value, 'phone_number')
        }
    })
    .value();

console.log('result', result)

2.使用纯JS



var origArr = [{
  phone_number: '777',
  type: 'ORDER_SMS'
}, {
  phone_number: '777',
  type: 'ORDER_CALL'
}, {
  phone_number: '999',
  type: 'ORDER_SMS'
}];

function groupBy(arr, key) {
  var newArr = [],
    types = {},
    newItem, i, j, cur;
  for (i = 0, j = arr.length; i < j; i++) {
    cur = arr[i];
    if (!(cur[key] in types)) {
      types[cur[key]] = {
        type: cur[key],
        data: []
      };
      newArr.push(types[cur[key]]);
    }
    types[cur[key]].data.push(cur);
  }
  return newArr;
}

console.log(groupBy(origArr, 'type'));
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以通过多种方式实现,这只是其中之一

var grouped = _.groupBy(result, function(obj) {
    return obj.type;
});
result = _.keys(grouped).map(function(key) {
    var newObj = {};
    newObj[key] = _.pluck(grouped[key], 'phone_number').join(' ');
    return newObj
});