通过比较两个列表来获取值

时间:2020-07-10 15:14:04

标签: angular typescript angular8

需要比较两个ID,并获取symptomValue并推入症状FormArray。

"partcipantData": [
    {
      "symptomId": 8651,
      "symptomValue": "N"
    },
    {
      "symptomId": 8646,
      "symptomValue": "N"
    },
    {
      "symptomId": 8642,
      "symptomValue": "N"
    }
]


var symptomsParams = [
  {
    "id": 8651,
    "value": "Abdominal pain"
  },
  {
    "id": 8646,
    "value": "Chest pain"
  },
  {
    "id": 8642,
    "value": "Cough"
  }
]

需要比较两个ID,并获取symptomValue并推入症状FormArray。

 this.symptomsParams.forEach(childObj =>{
              let val = this.partcipantData.filter(obj => obj.symptomId == childObj.id)
            
              this.symptomsFormArray.push(new FormControl(val.symptomValue))
              });
              

这里val值始终返回未定义,还有其他方法可以实现吗?

1 个答案:

答案 0 :(得分:1)

假设您要从symptomsParams过滤参与者数据,只需使用数组映射和过滤器

const symptomsParams = [
    {
      "symptomId": 8651,
      "symptomValue": "N"
    },
    {
      "symptomId": 8646,
      "symptomValue": "N"
    },
    {
      "symptomId": 8642,
      "symptomValue": "N"
    }
];

const partcipantData = [
  {
    "id": 8651,
    "value": "Abdominal pain"
  },
  {
    "id": 8646,
    "value": "Chest pain"
  },
  {
    "id": 8642,
    "value": "Cough"
  }
];

const symptomIds = symptomsParams.map(s => s.symptomId);
const filteredSymptomValues = partcipantData
  .filter(p => symptomIds.includes(p.id))
  .map(p => p.value);

console.log(filteredSymptomValues);

然后将其症状从数组中推送出去

filteredSymptomValues.forEach(value => this.symptomsFormArray.push(new FormControl(value)))