将 2 个对象数组组合成 1 个对象数组(重构请求)

Combining 2 arrays of objects into 1 array of objects (refactoring request)

正在寻找更优化的方法。

资源数组:

const users = [
    { id: 1, name: 'Vasya', postIds: [11, 22] },
    { id: 2, name: 'Petya', postIds: [33] },
    { id: 3, name: 'Roma', postIds: [44] },
];

const posts = [
    { id: 11, title: 'How to eat' },
    { id: 22, title: 'How to drink' },
    { id: 33, title: 'How to breath' },
    { id: 44, title: 'How to swim' },
];

预期结果

   const expectedResult = [
      {
        id: 1,
        name: 'Vasya',
        posts: [
          { id: 11, title: 'How to  eat' },
          { id: 22, title: 'How to drink' },
        ]
      },
      {
        id: 2,
        name: 'Petya',
        posts: [{ id: 33, title: 'How to breath' },]
      },
      {
        id: 3,
        name: 'Roma',
        posts: [{ id: 44, title: 'How to swim' }]
      },
    ]

我在做什么:

const expectedOutput = users.map(({id,name,postIds})=>({id,name,posts:posts.filter(post=>postIds.includes(post.id))}))

问题是 - 我进行了太多次迭代(映射、筛选和包含),认为有可能以更漂亮的方式进行。对于重构的任何想法都将非常有用

你的解决方案看起来不错,但如果你想降低复杂性,你可以先创建一个 table post 的查找,然后映射到它。

这里使用 Map for the lookup table, nested map() calls to iterate over each object/postIds array, and a nullish ?? 检查 return 一个只有 id 的对象,如果没有找到匹配的 post。

const users = [
  { id: 1, name: 'Vasya', postIds: [11, 22] },
  { id: 2, name: 'Petya', postIds: [33] },
  { id: 3, name: 'Roma', postIds: [44] },
];

const posts = [
  { id: 11, title: 'How to eat' },
  { id: 22, title: 'How to drink' },
  { id: 33, title: 'How to breath' },
  { id: 44, title: 'How to swim' },
];

const postsMap = new Map(posts.map((post) => [post.id, post]));

const result = users.map(({ postIds, ...user }) => ({
  ...user,
  posts: postIds.map((id) => postsMap.get(id) ?? { id }),
}));

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