尝试将对象数组简化为相似但汇总的对象数组

时间:2018-06-19 19:57:45

标签: javascript typescript reduce

所以我有一个看起来像这样的对象数组:

dataArray = [
    {Revenue: 5, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 10, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 5, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 1, Date: "2018-06-13T00:00:00", DateString: "6/13/2018"},
    {Revenue: 4, Date: "2018-06-13T00:00:00", DateString: "6/13/2018"}
]

我需要将其减少为另一个对象数组,如下所示:

reducedDataArray = [
    {Revenue: 20, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 5, Date: "2018-06-13T00:00:00", DateString: "6/13/2018"}
]

基本上,如果日期相同,则需要对收入进行汇总,以便同一日期不会有多个实例。不幸的是,我仅限于我们的Typescript版本,因此我没有所有出色的ES6好东西来帮助您。我已经尝试过使用reduce()之类的方法,但是我认为不知道自己在做什么,再加上这种怪异的感觉,使我迷惑不解。

任何建议或见解将不胜感激!

2 个答案:

答案 0 :(得分:3)

您可以使用reduce创建带有日期键的对象,然后将该对象转换回数组。

let dataArray = [
    {Revenue: 5, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 10, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 5, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 1, Date: "2018-06-13T00:00:00", DateString: "6/13/2018"},
    {Revenue: 4, Date: "2018-06-13T00:00:00", DateString: "6/13/2018"}
]
// We need to specify the type parameter explicitly, as it will not be inffered from initial value 
let valuesObj = dataArray.reduce<{ [date: string]: typeof dataArray[number] }>((p, v) => {
    const existing = p[v.Date];
    if (existing) {
        existing.Revenue += v.Revenue
    } else {
        p[v.Date] = Object.assign({}, v); //Create a copy so as to not change the original when we sum 
    }
    return p;
}, {});


// You can use Object.values(valuesObj) if available 
let values = Object.keys(valuesObj).map(k => valuesaObj[k]);

游乐场link

答案 1 :(得分:1)

玩了一些循环,就可以了

dataArray = [
    {Revenue: 5, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 10, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 5, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"},
    {Revenue: 1, Date: "2018-06-13T00:00:00", DateString: "6/13/2018"},
    {Revenue: 4, Date: "2018-06-13T00:00:00", DateString: "6/13/2018"}
];

const getUnique=array=>{
  return array.filter((value, index, self)=> { 
      return self.indexOf(value) === index;
  });
}

let date=[];
let output=[];

for(const v of dataArray) date.push(v.Date);
for(const v of getUnique(date)){

  let revenue=0,date=v,dateString;
  for(const x of dataArray){
    if(x.Date==v) revenue+=x.Revenue;
    dateString=x.DateString;
  }

  output.push({
    Revenue:revenue,
    Date:v,
    DateString:dateString
  });

}

console.log(output);

jsfiddle link