将多个对象数组转换为单个数组,同时在公共键上合并对象

时间:2018-11-02 13:30:56

标签: javascript arrays object

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

const myArray = [
  {
    values: [
      { date: "2018-11-02", "value1": 3, "value2": 5 },
      { date: "2018-11-01", "value1": 8, "value2": 9 },
      { date: "2018-10-31", "value1": 4, "value2": 10 },
    ],
    customer: "Customer One"
  },
  {
    values: [
      { date: "2018-11-02", "value1": 3 },
      { date: "2018-11-01", "value1": 5 },
      { date: "2018-10-31", "value1": 8 },
    ],
    customer: "Customer Two"
  }
];

应该将对象的所有值相加(按日期),然后将结果作为新对象中客户的值

我想要的是这样的

result = [
  { date: "2018-11-02", "Customer One": 8, "Customer Two": 3 },
  { date: "2018-11-01", "Customer One": 17, "Customer Two": 5 },
  { date: "2018-10-31", "Customer One": 14, "Customer Two": 8 },
]

我有用于此的代码,但感觉对我来说太复杂了,但是由于某种原因,我无法将头放在更简单的方法上。

这是我的代码(也在codeandbox上:https://codesandbox.io/s/zvlpm167x):

const myArray = [
  {
    values: [
      { date: "2018-11-02", "value1": 3, "value2": 5 },
      { date: "2018-11-01", "value1": 8, "value2": 9 },
      { date: "2018-10-31", "value1": 4, "value2": 10 },
    ],
    customer: "Customer One"
  },
  {
    values: [
      { date: "2018-11-02", "value1": 3 },
      { date: "2018-11-01", "value1": 5 },
      { date: "2018-10-31", "value1": 8 },
    ],
    customer: "Customer Two"
  }
];

const flatArray = myArray.flat();

const sumObjectKeysExceptDate = object => Object.keys(object).reduce((sum, key) => {
  if (!Number.isNaN(parseInt(object[key], 10)) && key !== 'date') {
    return sum + parseInt(object[key], 10);
  }
  return sum;
}, 0);

const result = flatArray
  .reduce((acc, row) => [...acc, ...row.values.map(value => ({ [row.customer]: sumObjectKeysExceptDate(value), date: value.date }))], [])
  .reduce((acc, row) => {
    if (acc.find(innerrow => innerrow.date === row.date)) {
      return acc.map((innerrow) => {
        if (innerrow.date === row.date) {
          return { ...innerrow, ...row };
        }
        return innerrow;
      });
    }
    return [...acc, row];
  }, []);

console.log(result)

1 个答案:

答案 0 :(得分:1)

尝试关注

  • 使用date作为键创建一个对象,并将相应的结果对象作为值。并使用Object.values得到最终结果
  • 要构建对象,请在外部数组上使用Array.reduce,对于内部数组的每个值,请检查对象中是否存在日期条目。如果存在更新,则在对象中创建一个新条目。
  • 对于内部数组中的每个对象,对除日期以外的所有键的值求和,并将其设置在与customer名称键相对应的对象中。

const myArray = [{values: [{ date: "2018-11-02", "value1": 3, "value2": 5 },{ date: "2018-11-01", "value1": 8, "value2": 9 },{ date: "2018-10-31", "value1": 4, "value2": 10 },],customer: "Customer One"},{values: [{ date: "2018-11-02", "value1": 3 },{ date: "2018-11-01", "value1": 5 },{ date: "2018-10-31", "value1": 8 },],customer: "Customer Two"}];

let result = Object.values(myArray.reduce((a,c) => {
  c.values.forEach(({date, ...rest}) => {
    a[date] = a[date] || {date};
    a[date][c.customer] = Object.values(rest).reduce((d,e) => d + e);
  });
  return a;
}, {}));
console.log(result);