替换数组中的索引

I'm trying to understand how array works in typescript and I'm struggling to find any solutions on how to replace the index inside an array by a variable, for example with the datas as show below I would like to replace all index numbers by the part_id variable that is inside each index : enter image description here

例如,对于第一个索引,我想使用part_id等的26作为替代,而不是[0]。

这是一个代码示例(数据来自API,我获取了API返回的数组的副本并对其进行了修改,以便可以对它们执行forEach,而PatchValue则将onInit设置为值)

Component.ts

 initQuot(){
    this.service.checkExistQuot().subscribe(res => {
      this.quotArray = res;
      this.quotDetails = res.quotation.quotationdetail;
      let group = {};

      this.copy.forEach((val, index)=>
      {
        group[`longueur_${index}`] = '';
        group[`quantity_${index}`] = '';
        group['diameter1'] = '';
        group['diameter2'] = '';

      });
      this.dropForm = this.formBuilder.group(
        group
      );
 this.quotDetails.forEach( (myArray, index) => {
        this.copy.forEach( array1Ttem => {

          this.quotDetails.forEach( array2Item => {

            if(array1Ttem.part_id == array2Item.part_id){
              for (var i = 0; i < this.copy.length; i++) {
                this.copy[myArray.part_id] = this.copy[index];
                console.log(this.copy);
                let patchValue = {};
                this.copy[i].longueur = myArray.longueur; 
                this.copy[i].quantity = myArray.quantity; 
                patchValue[`longueur_${index}`] = this.copy[index].longueur;
                patchValue[`quantity_${index}`] = this.copy[index].quantity;
                this.dropForm.patchValue(patchValue);
              }
            }
            else{
                   console.log("No values matched");
            }

          })
        });
 })
    })
  }

如果有人知道解决方案/我应该怎样看待我的问题,我将不胜感激,谢谢

评论
  • 此1不2
    此1不2 回复

    可能会问,一旦声明从0开始,数组的索引值是否可以更改为1。答案是否定的。

    排序实际数组是您情况下的最佳解决方案:-

    list.sort((a,b) => a.part_id - b.part_id);
    
  • Rose
    Rose 回复

    It's not really feasible to alter the array indices, but you could achieve essentially any desired behaviors using array functions. For instance, if you want to order the array by the part_id, you could do list.sort((a, b) => (a.part_id > b.part_id) ? 1 : -1)