组合并添加2个数组typescript,lodash,下划线

时间:2016-09-18 15:38:39

标签: typescript lodash

我有一个对象数组,如下所示:

[  
  {date: '2016-09-10', 'Post': 5, 'Pickup': 2},  
  {date: '2016-09-11', 'Post': 8, 'Pickup': 2},  
  {date: '2016-09-12', 'Post': 0, 'Pickup': 2},  
  {date: '2016-09-12', 'Post': 3, 'Pickup': 0},  
  {date: '2016-09-13', 'Post': 1, 'Pickup': 2},  
  {date: '2016-09-13', 'Post': 1, 'Pickup': 0},  
]

我需要按日期组合对象并添加帖子+帖子和拾取+拾取,如下所示:

[  
  {date: '2016-09-10', 'Post': 5, 'Pickup': 2},  
  {date: '2016-09-11', 'Post': 8, 'Pickup': 2},  
  {date: '2016-09-12', 'Post': 3, 'Pickup': 2},  
  {date: '2016-09-13', 'Post': 2, 'Pickup': 2},  
] 

我更喜欢lodash和/或下划线 谢谢。

我开始使用这样的2个数组:

pickup = [  
      {date: '2016-09-11', 'Post': 8, 'Pickup': 2},  
      {date: '2016-09-12', 'Post': 3, 'Pickup': 0},  
      {date: '2016-09-13', 'Post': 1, 'Pickup': 0},  
    ]  

post = [  
      {date: '2016-09-10', 'Post': 5, 'Pickup': 2},  
      {date: '2016-09-12', 'Post': 0, 'Pickup': 2},  
      {date: '2016-09-13', 'Post': 1, 'Pickup': 2},  
    ]

我使用data = _.unionBy( post, pickup, 'date' );
_.uniqBy( data, 'date' );

2 个答案:

答案 0 :(得分:-1)

您可以使用reduce并在结果数组中为新日期创建新对象,或者仅添加到PostsPickups(如果已有):

var result = _.reduce(array, function (memo, el) {
  var d = _.find(memo, function(e) { return e.date === el.date });
  if (d) {
    d.Post += el.Post;
    d.Pickup += el.Pickup;
  } else {
    memo.push(_.clone(el));
  }
  return memo;
}, []);



var array = [  
  {date: '2016-09-10', 'Post': 5, 'Pickup': 2},  
  {date: '2016-09-11', 'Post': 8, 'Pickup': 2},  
  {date: '2016-09-12', 'Post': 0, 'Pickup': 2},  
  {date: '2016-09-12', 'Post': 3, 'Pickup': 0},  
  {date: '2016-09-13', 'Post': 1, 'Pickup': 2},  
  {date: '2016-09-13', 'Post': 1, 'Pickup': 0} 
];

var result = _.reduce(array, function (memo, el) {
  var d = _.find(memo, function(e) { return e.date === el.date });
  if (d) {
    d.Post += el.Post;
    d.Pickup += el.Pickup;
  } else {
    memo.push(_.clone(el));
  }
  return memo;
}, []);

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

var res = _.chain(array)
    .groupBy('date')
    .mapValues(function(dateArray) {
        return {
            'Post': _.chain(dateArray).map('Post').sum().value(),
            'Pickup': _.chain(dateArray).map('Pickup').sum().value(),
            'date': _.first(dateArray).date
        }
    })
    .values()
    .value();