gpt4 book ai didi

javascript - 比较两个 JSON 并创建一个具有共同值的 json

转载 作者:行者123 更新时间:2023-12-04 09:25:47 27 4
gpt4 key购买 nike

我想通过比较两个 JSON 来创建两个基于公共(public)属性值的 JSON 数组。

this.linkedParticipants =[
{
"id": 3,
"name": "Participant 2",
"email": "participant2@fico.com"
},
{
"id": 2,
"name": "Participant 1",
"email": "participant1@fico.com"
},
{
"id": 1,
"name": "Libin Varghese",
"email": "LibinVarghese@fico.com"
},
{
"id": 7,
"name": "Participant 5",
"email": "participant5@fico.com"
}
]
this.appointmentList = [
{
"id": 32,
"participant": {
"id": 1,
"name": "Libin Varghese",
"email": "LibinVarghese@fico.com"
}
},
{
"id": 33,
"participant": {
"id": 7,
"name": "Participant 5",
"email": "participant5@fico.com"
}
}
]
this.invitedList = [];
this.confirmedList = [];
let temp = {}
this.linkedParticipants.forEach((participant, i) => {
this.appointmentList.forEach((appointment, j) => {
if (appointment.participant.name.indexOf(participant.name)) {
temp = {
'participant': participant
}
this.invitedList.push(temp);
}
else {
this.confirmedList.push(appointment)
}
})
})
但是代码没有按预期工作,因为 this.invitedList 的两个值给出了重复值。我认为我的比较条件有一些问题。

最佳答案

您可以通过 filter() 的不同组合来实现此目的。 :

 var linkedParticipants =[
{
"id": 3,
"name": "Participant 2",
"email": "participant2@fico.com"
},
{
"id": 2,
"name": "Participant 1",
"email": "participant1@fico.com"
},
{
"id": 1,
"name": "Libin Varghese",
"email": "LibinVarghese@fico.com"
},
{
"id": 7,
"name": "Participant 5",
"email": "participant5@fico.com"
}
];
var appointmentList = [
{
"id": 32,
"participant": {
"id": 1,
"name": "Libin Varghese",
"email": "LibinVarghese@fico.com"
}
},
{
"id": 33,
"participant": {
"id": 7,
"name": "Participant 5",
"email": "participant5@fico.com"
}
}
];


var confirmedList = appointmentList.filter((a) => {
return linkedParticipants.find((p) => p.id === a.participant.id);
});

var invitedList = linkedParticipants.filter((p) => {
return !appointmentList.find((a) => p.id === a.participant.id);
});

console.log(confirmedList)
console.log(invitedList)

关于javascript - 比较两个 JSON 并创建一个具有共同值的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63014611/

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