【发布时间】:2020-11-10 20:08:44
【问题描述】:
我想通过比较两个 JSON 来创建两个基于公共属性值的 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 的两个值给出了重复值。我认为我的比较条件存在一些问题。
【问题讨论】:
-
indexOf返回字符串中子字符串的索引。在这里,索引是0,这是假的。当名称匹配时,您的if条件不会通过。您可能想使用includes而不是indexOf -
@blex 但我仍然收到重复项
标签: javascript jquery typescript