我想将所有2个人之间的消息分组(聊天)。我是作者还是收件人都没关系。

假设这个示例代码。

const messages = [
  { id: '100', text: 'aaa', author: { id: '1' }, receiver: { id: '2' } },
  { id: '101', text: 'bbb', author: { id: '2' }, receiver: { id: '1' } },
  { id: '102', text: 'ccc', author: { id: '3' }, receiver: { id: '1' } },
]


想象一下,我的用户ID = 1,所以我想得到这个:

const chats = [
  {
    chatName: 'Name of user ID 2', messages: [
      { id: '100', text: 'aaa', author: { id: '1' }, receiver: { id: '2' } },
      { id: '101', text: 'bbb', author: { id: '2' }, receiver: { id: '1' } },
    ]
  },
  {
    chatName: 'Name of user ID 3', messages: [
      { id: '102', text: 'ccc', author: { id: '3' }, receiver: { id: '1' } },
    ]
  }
];


我如何用Lodash做到这一点?

最佳答案

不确定lodash,但是您可以使用普通js-reducemap来获取该结构



const messages = [{
    id: '100',
    text: 'aaa',
    author: {
      id: '1'
    },
    receiver: {
      id: '2'
    }
  },
  {
    id: '101',
    text: 'bbb',
    author: {
      id: '2'
    },
    receiver: {
      id: '1'
    }
  },
  {
    id: '102',
    text: 'ccc',
    author: {
      id: '3'
    },
    receiver: {
      id: '1'
    }
  },
];

function groupByPair(arr) {
  return [
    ...arr.reduce((a, b) => {
      let {
        author,
        receiver
      } = b;
      let s = [author.id, receiver.id].sort().join('-');
      a.set(s, a.has(s) ? a.get(s).concat(b) : [b]);
      return a;
    }, new Map)
  ].map(e => ({
    chatName: 'Name of user ID ' + e[0].substring(e[0].indexOf('-') + 1),
    messages: e[1]
  }));
}
console.log(groupByPair(messages));

10-06 05:10