例如,我有两个数组“ StudentInfo”
[
{
"id": "1234",
"name": "A"
},
{
"id": "1134",
"name": "B"
},
{
"id": "2234",
"name": "C"
},
{
"id": "3234",
"name": "D"
}
]
和“ GoodStudentList”
[
"1234",
"1134"
]
那么我该如何在StudentInfo上添加一个有关Student类型的属性,取决于GoodStudentList,如果他们的ID在好的列表中,那么他们的类型就很好,否则他们的类型是Normal:
[
{
"id": "1234",
"name": "A",
"type": "Good"
},
{
"id": "1134",
"name": "B"
"type": "Good"
},
{
"id": "2234",
"name": "C"
"type": "Normal"
},
{
"id": "3234",
"name": "D",
"type": "Normal"
}
]
对不起,我知道这可能很简单,但我真的不明白JS qwq中的映射内容
答案 0 :(得分:3)
您可以使用forEach()
遍历students数组,并使用includes()
测试每个ID是否在良好列表中。然后在遍历学生时根据结果添加正确的属性:
let StudentInfo = [{"id": "1234","name": "A"},{"id": "1134","name": "B"},{"id": "2234","name": "C"},{"id": "3234","name": "D"} ]
let GoodStudentList = ["1234","1134"]
StudentInfo.forEach(student => {
student.type = GoodStudentList.includes(student.id) ? "Good" : "Normal"
})
console.log(StudentInfo)
答案 1 :(得分:1)
您可以在StudentInfo
数组上使用map方法,对于每个元素,检查该对象的ID是否存在于GoodStudentList
中。看起来可能像这样:
StudentInfo = StudentInfo.map((student) => {
if (GoodStudentList.indexOf(student.id) >= 0) {
student.type = 'Good';
} else {
student.type = 'Normal';
}
})
在这里,您正在检查每个学生的学生ID的索引是否大于0(意味着它存在于数组中)。如果它在数组中不存在,它将返回-1,因此不通过条件。返回的是StudentInfo数组,所有学生都已修改为现在包括type属性。
答案 2 :(得分:0)
使用简单的旧迭代:
let list = [
{
"id": "1234",
"name": "A"
},
{
"id": "1134",
"name": "B"
},
{
"id": "2234",
"name": "C"
},
{
"id": "3234",
"name": "D"
}
];
let good = [
"1234",
"1134"
];
for (let key in list){
for (let i of good){
if (i === list[key].id){
list[key].type = "Good";
break;
}
else list[key].type = "Neutral";
}
}
console.log(list);