【问题标题】:Array.find with Array.map in JavascriptArray.find 与 Array.map 在 Javascript
【发布时间】:2021-12-29 04:58:02
【问题描述】:

我有两个数组,在第一个数组中我存储了一些用户数据。其次,我存储用户的基本数据。

const usersData = [{ userId: 1, age: 18 }];
const users = [{id: 1, name: 'Alex'}];

我在下面写了一些简单的代码:

const result = usersData.map(userData => {
    return {
        ...userData,
        userName: users.find(user => user.id === userData.userId).name
    }
})

之后,我得到了结果:

const result = [{ userId: 1, age: 18, name: "Alex" }];

问题是:如何以更简单的方式编写此解决方案?也许应该使用“Lodash”库?


抱歉,我的英语不太好。

【问题讨论】:

  • 什么需要更简单?
  • 这一行:userName: users.find(user => user.id === userData.userId).name

标签: javascript arrays merge


【解决方案1】:

没有什么比这种方式更简单的了,但是您可以对其进行优化,这样您就不必为每个键都使用find。为此,您可以在此处使用Map

Note: If are trying to use any library, then under the hood they might be using the same method

const usersData = [{ userId: 1, age: 18 }];
const users = [{id: 1, name: 'Alex'}];

const usersDict = new Map();  // dictionary for users
users.forEach(o => usersDict.set(o.id, o));

const result = usersData.map(user => ({ ...user, username: usersDict.get(user.userId)?.name}))

console.log(result);

【讨论】:

    【解决方案2】:

    对于较大的数据集,最好使用不同的数据结构来提高查找性能并减少运行时间。

    const usersData = [{ userId: 1, age: 18 }];
    const users = [{id: 1, name: 'Alex'}];
    const usersById = Object.fromEntries(users.map(user => ([user.id, user])));
    
    const result = usersData.map(userData => {
        return {
            ...userData,
            userName: usersById[userData.userId]?.name
        }
    })
    
    console.log(result);

    【讨论】:

      猜你喜欢
      • 2020-12-12
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-05
      • 2010-09-05
      相关资源
      最近更新 更多