如何连接数组中的两个对象

How to join two objects in array

我想按日期标签过滤数据集数组中的两个对象。我在 react-chartjs-2 中使用。不知道怎么过滤。

示例:

First Object : {
    "id": 2,
    "customer_id": 4,
    "date": "2019-05-15T21:00:00.000Z",
    "wbc": 15,
    "vitamin": 14
}
Second Object : {
    "id": 3,
    "customer_id": 4,
    "date": "2022-05-22T21:00:00.000Z",
    "wbc": 20,
    "vitamin": 5
}

我需要这个:

datasets: [
      {
        label: "WBC",
        data: [
          { x: "2019-05-15", y: 15 },
          { x: "2022-05-22", y: 20 },
        ],
        backgroundColor: "#003f5c",
        pointRadius: 8,
        pointHoverRadius: 8,
      },
      {
        label: "Vitamin",
        data: [
          { x: "2019-05-15", y: 14 },
          { x: "2022-05-22", y: 5 },
        ],
        backgroundColor: "#ffa600",
        pointRadius: 8,
        pointHoverRadius: 8,
      },
    ],

我会这样做:

  1. 将项目放在一个数组中,以便更容易管理;
  2. 使用数据集中所需的键创建一个数组:(wbcvitamin 等...)和自定义设置对于每个键(bg-color,等等...);
  3. 将键数组缩减为包含具有您期望的形状的对象的数据集数组:

const items = [{
    id: 2,
    customer_id: 4,
    date: '2019-05-15T21:00:00.000Z',
    wbc: 15,
    vitamin: 14,
  },
  {
    id: 3,
    customer_id: 4,
    date: '2022-05-22T21:00:00.000Z',
    wbc: 20,
    vitamin: 5,
  },
];

const keys = [{
    type: 'wbc',
    settings: {
      backgroundColor: '#003f5c',
      pointRadius: 8,
      pointHoverRadius: 8,
    },
  },
  {
    type: 'vitamin',
    settings: {
      backgroundColor: '#ffa600',
      pointRadius: 8,
      pointHoverRadius: 8,
    },
  },
];

const datasets = keys.reduce((a, k) => {
  const o = {
    label: k.type.toUpperCase(),
    data: items.map((i) => ({
      x: new Date(i.date).toLocaleDateString(),
      y: i[k.type],
    })),
    ...k.settings,
  };
  a.push(o);
  return a;
}, []);

console.log(datasets);