gpt4 book ai didi

javascript - 假设我有两个包含相关数据的数组。如何搜索第一个数组并返回数组 1 和数组 2 之间合并的相关数据?

转载 作者:行者123 更新时间:2023-11-28 14:19:47 24 4
gpt4 key购买 nike

假设我有 2 个数组 usersuserCity。我想映射通过用户数组返回更新的用户对象 与基于相关 userIduserCity 数组合并的 city 数据

我收到错误:

    > *TypeError: Cannot read property 'city' of undefined
> at user.map.u (eval at <anonymous> (:7:47),*

const users = [
{ userId: 1, name: "Jim", age: 25 },
{ userId: 2, name: "Rens", age: 15 },
{ userId: 3, name: "Ed", age: 5 }
];

const userCity = [{ userId: 1, city: "TX" }, { userId: 3, city: "NY", age: 5 }];

const info = users.map(u => {
return {
...u,
city: userCity.find(uc => {
return uc.userId === u.userId;
}).city
};
});

console.log(info);

注意:我在某处读到高阶函数是同步的,因此我希望映射函数返回值并将它们分配给信息变量。因此,我希望 console.log 输出是一个数组,其中包含基于 userId 的合并用户和城市信息

[{ userId: 1, name: "Jim", age: 25, city: "TX" },

{ userId: 3, name: "Ed", age: 5, city: "NY" }]

最佳答案

您不需要遍历users,而是希望遍历userCity,因为您只想将数据合并到该对象数组中(而不是相反) .

考虑到这一点,当您迭代 userCity 时,只需使用 Array.prototype.find() 从 users 数组中获取匹配的用户,使用强制 userID 匹配的谓词/回调:

const users = [
{ userId: 1, name: "Jim", age: 25 },
{ userId: 2, name: "Rens", age: 15 },
{ userId: 3, name: "Ed", age: 5 }
];

const userCity = [{ userId: 1, city: "TX" }, { userId: 3, city: "NY", age: 5 }];

const info = userCity.map(c => {
const user = users.find(u => u.userId = c.userId);
return {...c, ...user};
});

console.log(info);

关于javascript - 假设我有两个包含相关数据的数组。如何搜索第一个数组并返回数组 1 和数组 2 之间合并的相关数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55668470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com