如何按日期合并/分组数组对象的两个值

时间:2019-07-11 13:23:46

标签: javascript object lodash

我正在尝试使用Amchart Multiple Values显示图形,该信息来自ElasticSearch。这是我的JS代码:

$.get(URI).then(resp => JSON.parse(resp))
            .then(values => {
                console.log(values)
                var data = [],
                values.map(e => e._source) //From Elastic the info is inside '_source' key  
                    .map((n, i) => {
                        n.date = moment(n.date).format('Y-MM-DD');
// I'm trying to format date, because it cames with Hour:Min:Sec and if I 
// try to compare dates it wont be equal (NOT USING IN THIS ATTEMPT)
                        if (n.warehouse.name === 'General') {
                            data.push({date: n.date, general: n.assessment});
                        } else {
                            data.push({date: n.date, intransit: n.assessment});
                        }

                    });

            })
            .fail(err => console.error(err.response));

这是带有以下代码的输出:


0: {date: "2019-07-10", intransit: 1234.23}
1: {date: "2019-07-10", general: 1234.23}
2: {date: "2019-07-12", intransit: 1234.23}
3: {date: "2019-07-12", general: 1234.23}

如您所见,日期是重复的,我如何合并/分组两者,但又不丢失值? 信息必须是这样的:

0: {date: "2019-07-10", intransit: 1234.23, general: 1234.23}
2: {date: "2019-07-12", intransit: 1234.23, general: 1234.23}

如果您无法从Elastic中看到结构,则这是console.log(values)的输出:

_source: {date: "2019-07-10", assessment: 123.12, 
warehouse: {id: 1, name: "General"}

我已经尝试使用Lodash / UndercoreJS,循环等...什么也没有。如果您知道任何建议或任何有关此的信息,将不胜感激。 谢谢。

2 个答案:

答案 0 :(得分:0)

使用reduce()创建groupBy对象或使用日期作为键的Map,然后返回values

const data = [ {date: "2019-07-10", intransit: 1234.23}, {date: "2019-07-10", general:1234.23}, {date: "2019-07-12", intransit: 1234.23},{date: "2019-07-12", general:1234.23}]

const res = Object.values(
  data.reduce((a, c) => {
    a[c.date] = a[c.date] || {};
    Object.assign(a[c.date], c);
    return a;
  }, {})
)


console.log(res)

答案 1 :(得分:0)

这是基于Lodash-fp

的解决方案
const dateMerger = _.flow([
    _.groupBy('date'),
    _.values,
    _.map(_.reduce(_.merge, {}))
]);

const dateData = [
    {date: "2019-07-10", intransit: 1234.23},
    {date: "2019-07-10", general: 1234.23},
    {date: "2019-07-12", intransit: 1234.23},
    {date: "2019-07-12", general: 1234.23}
];

console.log(dateMerger(dateData));

enter image description here