javascript 合并按日期分组的数组

qltillow  于 2023-04-28  发布在  Java
关注(0)|答案(2)|浏览(195)

我有两个聊天消息数组,每个数组代表给定日期的消息。我必须将这两个数组合并为一个具有相同日期格式的对象。该对象应包含来自两个数组的所有消息,并合并每个日期的消息。
数据如下:

const data1 = {
  messages: {
    "27-04-2023": [
      {
        id: "SOkXFGtTwh",
      },
      {
        id: "i3NrqNyG9P",
      },
      {
        id: "lCmxr4rc5T",
      },
    ]
  }
};

const data2 = {
  messages: {
    "27-04-2023": [
      {
        id: "V9QzRgl6ji",
      },
      {
        id: "K5wfD-kX8W",
      }
    ],
    "24-04-2023": [
      {
        id: "tuarzhHPwH",
      },
      {
        id: "cbxu_dAeAj",
      },
      {
        id: "9xJpEJGUnm",
      }
    ]
  },
};

如何合并它们以获得以下输出?

const data1 = {
  messages: {
    "27-04-2023": [
      {
        id: "SOkXFGtTwh"
      },
      {
        id: "i3NrqNyG9P"
      },
      {
        id: "lCmxr4rc5T"
      },
      {
        id: "V9QzRgl6ji"
      },
      {
        id: "K5wfD-kX8W"
      }
    ],

    "24-04-2023": [
      {
        id: "tuarzhHPwH"
      },
      {
        id: "cbxu_dAeAj"
      },
      {
        id: "9xJpEJGUnm"
      }
    ]
  }
};

执行这样的任务的最佳方式是什么?

nvbavucw

nvbavucw1#

你可以考虑使用for-in和spread运算符来合并数组的两个对象:

const data1 = { messages: { '27-04-2023': [{ id: 'SOkXFGtTwh' }, { id: 'i3NrqNyG9P' }, { id: 'lCmxr4rc5T' }] }};
const data2 = { messages: { '27-04-2023': [{ id: 'V9QzRgl6ji' }, { id: 'K5wfD-kX8W' }], '24-04-2023': [{ id: 'tuarzhHPwH' }, { id: 'cbxu_dAeAj' }, { id: '9xJpEJGUnm' }] }};

function merge(obj1, obj2) {
  const output = {};
  for (const key in obj1) {
    output[key] = [...(obj1[key] || []), ...(obj2[key] || [])];
  }
  for (const key in obj2) {
    output[key] = [...(obj1[key] || []), ...(obj2[key] || [])];
  }
  return output;
}

console.log({ messages: merge(data1.messages, data2.messages) });
3lxsmp7m

3lxsmp7m2#

此版本将任意数量的此类对象合并为一个,只允许后面对象的属性值覆盖前面对象的同名属性值,但messages除外,它会得到特殊处理:抓取所有messages属性,将它们转换为entries的平面列表,并将结果折叠回单个对象:

const mergeDates = (...ds) => ({
  ... Object .assign ({}, ...ds),
  messages: ds .flatMap (d => Object .entries (d .messages)) 
               .reduce ((a, [k, vs]) => ((a [k] = (a [k] ?? []) .concat (vs)), a), {})
})

const data1 = {messages: {"27-04-2023": [{id: "SOkXFGtTwh"}, {id: "i3NrqNyG9P"}, {id: "lCmxr4rc5T"}]}}
const data2 = {messages: {"27-04-2023": [{id: "V9QzRgl6ji"}, {id: "K5wfD-kX8W"}], "24-04-2023": [{id: "tuarzhHPwH"}, {id: "cbxu_dAeAj"}, {id: "9xJpEJGUnm"}]}}

console .log (mergeDates (data1, data2))
.as-console-wrapper {max-height: 100% !important; top: 0}

如果messages是您唯一的属性,则可以删除Object .assign行。相反,如果您还需要对messages以外的其他属性进行特殊处理,则可以很容易地添加与messages并行的其他属性。

相关问题