【问题标题】:Combining 2 arrays of objects into 1 array of objects (refactoring request)将 2 个对象数组组合成 1 个对象数组(重构请求)
【发布时间】:2021-11-11 20:48:58
【问题描述】:

正在寻找更优化的方法。

资源数组:

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))}))

问题是 - 我正在做太多的迭代(映射、过滤和包含),我认为有可能以更漂亮的方式来做。对任何重构的想法都会很感激

【问题讨论】:

    标签: javascript arrays json filter reduce


    【解决方案1】:

    您的解决方案看起来不错,但如果您想降低复杂性,您可以先创建一个帖子查找表,然后对其进行映射。

    这里使用Map 查找表,嵌套map() 调用以迭代每个对象/postIds 数组,如果没有找到匹配的帖子,则使用无效的?? 检查以返回仅具有id 的对象.

    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; }

    【讨论】:

    • 哇!看起来真棒!有趣的方法,以前从未使用过新地图
    • 很高兴它有帮助。如果您需要兼容性,可以将 Map 替换为对象。
    • 不不,没关系
    猜你喜欢
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2014-08-30
    • 1970-01-01
    • 2011-11-01
    相关资源
    最近更新 更多