gpt4 book ai didi

javascript - 根据另一个对象数组过滤对象数组并返回合并数组

转载 作者:行者123 更新时间:2023-12-03 01:16:59 25 4
gpt4 key购买 nike

我有一个像这样的对象数组:

phoneContacts= [
{
firstName: "aaaa",
lasttName: "aaaa",
phoneNumbers: [{id: "1", label: "mobile", number: "09121111111"},{id: "1", label: "home", number: "02188888888"}]
},
{
firstName: "bbbb",
lasttName: "bbbb",
phoneNumbers: [{id: "1", label: "mobile", number: "09122222222"},{id: "1", label: "home", number: "02177777777"}],
},
...]

我想用这样的数组过滤它:

registeredUsers= [
{
ID: 1,
CellPhone: "09123333333"
},
{
ID: 2,
CellPhone: "09121111111"
},
...]

并返回:

contactsMergerdWithID= [
{
ID: 1,
firstName: "aaaa",
lasttName: "aaaa",
phoneNumbers: [{id: "1", label: "mobile", number: "09121111111"},{id: "1", label: "home", number: "02188888888"}]
},
{
ID: 0, // or without ID
firstName: "bbbb",
lasttName: "bbbb",
phoneNumbers: [{id: "1", label: "mobile", number: "09122222222"},{id: "1", label: "home", number: "02177777777"}]
},
...]

如果第一个数组的任何手机号码与第二个数组中的 CellPhone 匹配,我想返回第二个数组中具有匹配 ID 字段的第一个数组。我怎样才能做到这一点?

最佳答案

const registeredUsers= [ {
ID: 1,
CellPhone: "09123333333"
}, {
ID: 2,
CellPhone: "09121111111"
}];

phoneContacts= [ {
firstName: "aaaa",
lasttName: "aaaa",
phoneNumbers: [{id: "1", label: "mobile", number: "09121111111"},{id: "1", label: "home", number: "02188888888"}]
}, {
firstName: "bbbb",
lasttName: "bbbb",
phoneNumbers: [{id: "1", label: "mobile", number: "09122222222"},{id: "1", label: "home", number: "02177777777"}],
}]

const contactsMergerdWithID = phoneContacts.map(contact => {
const mobile = contact.phoneNumbers.find(phoneNumber => phoneNumber.label === 'mobile')
const userfound = registeredUsers.find(user => user.CellPhone === mobile.number);
return userfound ? { ...contact, ID: userfound.ID } : contact;
// incase you dont want `phoneContacts` without `ID`, you can just return `false` instead of `contact` and put `.filter(Boolean)` after the `.map()`
});

console.log(contactsMergerdWithID);

关于javascript - 根据另一个对象数组过滤对象数组并返回合并数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51964271/

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