想要合并两个对象并创建值数组[关闭]

问题描述 投票:0回答:1

我有两个具有相同键和值名称 DateYMD 的对象。我想合并这两个对象并想创建新对象。

当前对象数据:

[{
          "Id": "1",
          "date": "2024-12-05T00:00:00",
          "DateYMD": 20241205,
          "bookTimeFrom": "2024-12-05T08:00:00",
          "bookTimeTo": "2024-12-05T13:00:00"
        },
        {
          "Id": "2",
          "date": "2024-12-05T00:00:00",
          "DateYMD": 20241205,
          "bookTimeFrom": "2024-12-05T14:00:00",
          "bookTimeTo": "2024-12-05T18:00:00"
        }]

我正在尝试使用 object.assign 方法来实现此目的,但没有按预期工作。

所需输出:

{
         "date": "2024-12-05T00:00:00",
         "DateYMD": 20241205,
         "Id": ["1","2"],
         "bookTimeFrom": ["2024-12-05T08:00:00", "2024-12-05T14:00:00"],
         "bookTimeTo": ["2024-12-05T13:00:00", "2024-12-05T18:00:00"]
     };
javascript arrays vue.js javascript-objects
1个回答
0
投票

收集对象键下集合中的值,然后将集合转换为数组:

const arr = [{
          "Id": "1",
          "date": "2024-12-05T00:00:00",
          "DateYMD": 20241205,
          "bookTimeFrom": "2024-12-05T08:00:00",
          "bookTimeTo": "2024-12-05T13:00:00"
        },
        {
          "Id": "2",
          "date": "2024-12-05T00:00:00",
          "DateYMD": 20241205,
          "bookTimeFrom": "2024-12-05T14:00:00",
          "bookTimeTo": "2024-12-05T18:00:00"
        }]


const sets = arr.reduce((r, obj) => (Object.entries(obj).forEach(([k, v]) => (r[k] ??= new Set).add(v)), r), {});
const out = Object.entries(sets).reduce((r, [k, v]) => (r[k] = [...v], r), {});

console.log(out);

© www.soinside.com 2019 - 2024. All rights reserved.