繁体   English   中英

通过与另一个对象(JavaScript)比较,有条件地向JSON对象添加新属性

[英]Add a new attribute to JSON object conditionally by comparing with another object (JavaScript)

例如,我有两个数组“ 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中的映射内容

您可以使用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) 

您可以在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属性。

使用简单的旧迭代:

 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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM