简体   繁体   English

Array.find 与 Array.map 在 Javascript

[英]Array.find with Array.map in Javascript

I have two arrays, in the first one I store some user data.我有两个 arrays,在第一个中我存储了一些用户数据。 In the second, I store the basic data about the users.其次,我存储有关用户的基本数据。

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

I wrote some simple code below:我在下面写了一些简单的代码:

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

After that, I get the result:之后,我得到结果:

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

The question is: how can you write this solution in a simpler way?问题是:如何以更简单的方式编写此解决方案? Maybe should use the library "Lodash"?也许应该使用库“Lodash”?


Sorry, my English is not so good.对不起,我的英语不太好。

There is nothing simpler than this way, but you can optimise it so that you don't have to use find for every key.没有什么比这种方式更简单的了,但是您可以对其进行优化,这样您就不必对每个键都使用find了。 For that you can use Map here.为此,您可以在此处使用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);

For larger datasets, it's better to use a different data structure to increase the performance of the lookup and reduce the runtime.对于较大的数据集,最好使用不同的数据结构来提高查找性能并减少运行时间。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM