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

问题描述

得到这个数组:

var arr =  [
      {
        series: [
          {
            "name": 2014,
            "data": [19, 17, 15, 12, 10, 10, 12, 10, 11, 14, 14, 18]
          },
          {
            "name": 2015,
            "data": [18, 17, 16, 12, 10, 7, 6, 8, 8, 11, 15, 30]
          },
        ]
      },
      {
        series: [
          {
            "name": 2014,
            "data": [32, 17, 15, 12, 33 10, 33, 10, 11, 14, 14, 18]
          },
          {
            "name": 2015,
            "data": [45, 10, 12, 55, 77, 7, 6, 8, 8, 11, 33, 30]
          },
        ]
      },
    ]

我需要创建一个返回汇总序列的函数:

I need to create a function that returns a summrized series:

var series = [
  {
    year: '2014',
    data: [51, 34....],
  },
  {
    year: '2015',
    data: [63, 27....],
  }
]

我可以循环来做到这一点,但我想有一些使用下划线的聪明方法吗?可能使用 reduce 函数.关于如何做到这一点的任何想法?

I could to loops to do this but I guess there is some smart way of doing with underscore? Probably with the reduce function. Any ideas of how to do this?

推荐答案

var arr = [{
    "series": [{
        "name": 2014,
        "data": [19, 17, 15, 12, 10, 10, 12, 10, 11, 14, 14, 18]
    }, {
        "name": 2015,
        "data": [18, 17, 16, 12, 10, 7, 6, 8, 8, 11, 15, 30]
    }]
}, {
    "series": [{
        "name": 2014,
        "data": [19, 17, 15, 12, 10, 10, 12, 10, 11, 14, 14, 18]
    }, {
        "name": 2015,
        "data": [18, 17, 16, 12, 10, 7, 6, 8, 8, 11, 15, 30]
    }]
}];


_.chain(arr)
    .map('series')
    .flatten()
    .reduce(function(object, value) {
        object[value.name] = !object[value.name] ? value.data : _.union(object[value.data], value.data);
        return object;
    }, {})
    .reduce(function(arr, value, key) {
        arr.push({
            year: key,
            data: value
        });
        return arr;
    }, [])
    .value();

这篇关于汇总数组值,下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 15:34