簡體   English   中英

如何選擇特定的 object 然后將其推送到現有陣列中?

[英]How to pick an specific object then push it into an existing array?

api.get(`get-participant-reports/${this.userData.ind_id}`)
      .then((res) => {
        this.reportData = res.data;
        for (var i = 0; i < this.reportData.length; i++) {
          api.get(`get-not-eligible360/${this.reportData[i].id}`).then((res) => {
            this.reportData.push(res.data)
            console.log(this.reportData)
          });
        }
      });

我有2 api我想填充同一個variable ,所以我使用.push()將第二個 API 調用插入到同一個variable

這是它的樣子:

0:{
    "id": 30,
    "survey_template_name": "Big 5 Survey",
    "report_template_name": "5 Step Profile Report",
    "suborg_name": "Sandbox",
    "program_name": "MNET Testing",
    "iteration_name": "MNET2022 - Test July 2022",
}
1:{
    "id": 3280,
    "survey_template_name": "Big 5 Survey",
    "report_template_name": "5 Step Profile Report",
    "suborg_name": "Sandbox",
    "program_name": "MNET Testing",
    "iteration_name": "iteration-1a",
}
2:{
    "0": {
        "id": 30,
        "not_eligible": "1",
    }
}
3:{
    "0": {
        "id": 3280,
        "not_eligible": "1",
    }
}

我想要發生的是獲取not_eligible然后將其分別push送到具有相同id的現有variable中。 我怎樣才能做到這一點?

我假設您的響應數據為 object 數組,並且需要根據第一個響應數據的 id 在第一個響應數據中添加鍵not_eligible ,所以我有更新代碼它應該適合您。

    api.get(`get-participant-reports/${this.userData.ind_id}`)
          .then((res) => {
            this.reportData = res.data;
            for (var i = 0; i < this.reportData.length; i++) {
              api.get(`get-not-eligible360/${this.reportData[i].id}`).then((res) => {
                this.reportData.forEach(reportItem => {
                const existData = res.data.find(resItem => resItem.id === reportItem.id);
                  if (existData) {
                    reportItem.not_eligible = existData.not_eligible
                   }
                });
                console.log(this.reportData)
              });
            }
          });

嘗試使用findIndex ,如果找到設置 object 屬性:

api.get(`get-participant-reports/${this.userData.ind_id}`)
      .then((res) => {
        this.reportData = res.data;
        for (var i = 0; i < this.reportData.length; i++) {
          api.get(`get-not-eligible360/${this.reportData[i].id}`).then((res) => {
            let idx = this.reportData.findIndex(i => i.id == res['0'].id)
            if(idx > -1) this.reportData[idx].not_eligible = res['0'].not_eligible
          });
        }
      });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM