本文介绍了按Javascript对象键+数组分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用下划线将对象数组分组到一个较小的列表中:

I am trying to use underscore to group my array of objects in a smaller list:

    var list = [
  { Region: 'A', Vals: [ 7, 'H' ] },
  { Region: 'B', Vals: [ 40, 'H' ] },
  { Region: 'B', Vals: [ 24, 'VH' ] },
  { Region: 'C', Vals: [ 4, 'VH' ] },
  { Region: 'A',Vals: [ 40, 'VH' ] }
  ];


    var groups = _.groupBy(list, function(value){
        return value.Region;
    });

var grouped = _.map(groups, function(group){
        return {
            Region: group[0].Region,
            Vals: group[0].Vals
        }
    });

哪一个会比较接近,但缺少一些Val。我希望基于键连接的 val数组。

Which will get somewhat close, but it is missing some of the Vals. I want the arrays of 'vals' concatenated based on keys.

   var list = [
  { Region: 'A', Vals: [ 7, 'H', 40, 'VH' ] },
  { Region: 'B', Vals: [ 40, 'H',  24, 'VH' ] },
  { Region: 'B', Vals: [ 24, 'VH' ] },
  { Region: 'C', Vals: [ 4, 'VH' ] }
  ];

推荐答案

list.reduce(function (memo, v) {
  if (memo[v.Region]) {
    memo[v.Region] = memo[v.Region].concat(v.Vals)
  } else {
    memo[v.Region] = v.Vals.slice()
  }
  return memo
}, {})

输出看起来像这样:

{
  A: [ 7, "H", 40, "VH" ],
  B: [40, "H", 24, "VH" ],
  C: [ 4, "VH" ]
}

这篇关于按Javascript对象键+数组分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 06:53