努力减少

Struggling to reduce

如果 'startDate' 相等,请寻求有关将所有账单合并或减少为对象数组的最佳方法的帮助。

来自这里:

{
    "id": 0,
    "startDate": "2020-01-10T07:00:00.000Z", //Same
    "endDate": "2020-01-24T07:00:00.000Z",
    "bills": {
      "name": "Bill 1",
    }
},
{
    "id": 1,
    "startDate": "2020-01-10T07:00:00.000Z", //Same
    "endDate": "2020-01-24T07:00:00.000Z",
    "bills": {
      "name": "Bill 2",
    }
}

对此:

{
    "id": 0,
    "startDate": "2020-01-10T07:00:00.000Z", 
    "endDate": "2020-01-24T07:00:00.000Z",
    "bills": [
               {"name": "Bill 1",},
               {"name": "Bill 2",}
             ]
}

遍历每个项目的数据并使用 startDate 的键构建一个对象。
如果键不存在,则添加键和值。
如果密钥已经存在,请附加账单。

const update = data => {
  const res = {};
  data.forEach(item => {
    if (!res[item.startDate]) {
      res[item.startDate] = { ...item, bills: [] };
    }
    res[item.startDate].bills.push(item.bills);
  });
  return Object.values(res);
};

const data = [
  {
    id: 0,
    startDate: "2020-01-10T07:00:00.000Z", //Same
    endDate: "2020-01-24T07:00:00.000Z",
    bills: {
      name: "Bill 1"
    }
  },
  {
    id: 1,
    startDate: "2020-01-10T07:00:00.000Z", //Same
    endDate: "2020-01-24T07:00:00.000Z",
    bills: {
      name: "Bill 2"
    }
  }
];

console.log(update(data));