gpt4 book ai didi

javascript - 根据键值比较合并两个对象数组

转载 作者:行者123 更新时间:2023-12-01 23:19:17 25 4
gpt4 key购买 nike

我正在尝试合并两个对象,它们都具有相同的相似键,但值不同。我希望他们保留不同的键,但将它们放在匹配的键值中

这是我的第一个对象,

const obj1 = [
{
"p_id": 1,
"name": "Peter",
"status" : "Active"
},
{
"p_id": 2,
"name": "Kane",
"status" : "Active"
},
{
"p_id": 3,
"name": "William",
"status" : "Inactive"
}
]


}

我的第二个对象,

const obj2 = [
{ p_id: 1, type: 'home', no: '+01 234 5678' },
{ p_id: 1, type: 'work', no: '+09 111 2223' },
{ p_id: 2, type: 'home', no: '+12 345 6789' },
]

其实我做了这样的事情,

 obj1.forEach((item) => {
Object.assign(item, {
phone: obj2.find(
(o) => o.p_id === item.p_id
)
});
});
// console.log(obj1) would be

[
{
"p_id": 1,
"name": "Peter",
"status" : "Active",
"phone" : {type: 'home', no: '+01 234 5678'}
},
{
"p_id": 2,
"name": "Kane"
"status" : "Active",
"phone" : {type: 'home', no: '+12 345 6789'}
},
{
"p_id": 3,
"name": "William"
"status" : "Inactive"
"phone" : undefined
}

]

但这不是我想要的。我想成为最终结果我需要的是这些数组之间的比较——最终结果应该是这样的:

const result = [
{
"p_id": 1,
"name": "Peter",
"status" : "Active",
"phone" : [
{type: 'home', no: '+01 234 5678'},
{type: 'work', no: '+09 111 2223'}
]
},
{
"p_id": 2,
"name": "Kane"
"status" : "Active",
"phone" : [
{type: 'home', no: '+12 345 6789'}
]
},
{
"p_id": 3,
"name": "William"
"status" : "Inactive"
"phone" : []
}

]

非常感谢您的帮助,谢谢!

最佳答案

你可以这样做:

const users = [
{
p_id: 1,
name: "Peter",
status: "Active",
},
{
p_id: 2,
name: "Kane",
status: "Active",
},
{
p_id: 3,
name: "William",
status: "Inactive",
},
];

const phoneNumbers = [
{ p_id: 1, type: "home", no: "+01 234 5678" },
{ p_id: 1, type: "work", no: "+09 111 2223" },
{ p_id: 2, type: "home", no: "+12 345 6789" },
];

const mergeArrays = (arr1, arr2) => {
return arr1.map((obj) => {
const numbers = arr2.filter((nums) => nums["p_id"] === obj["p_id"]);
if (!numbers.length) {
obj.phone = numbers;
return obj;
}
obj.phone = numbers.map((num) => ({ type: num.type, no: num.no }));
return obj;
});
};

const result = mergeArrays(users, phoneNumbers);
console.log(result);

解释:

使用filter 方法在phoneNumbers 数组中查找具有相同id 的所有对象。然后在匹配的电话号码上使用 map 方法循环并返回一个不带 id 的电话号码对象。

关于javascript - 根据键值比较合并两个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68313108/

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