簡體   English   中英

Angular-將數組復制到建模數組

[英]Angular - Copy array to modeled array

我需要從API Rest接收的數組中創建一個自定義數組。 我收到此模型:

export interface AreaEstadistica {
  id_area_estadistica: String;
  nombre: String;      
  id_distrito: String;
  calculos_estadisticos_pt: Array<CalculoEstadistico>;
}

export interface CalculoEstadistico {
  uso: string;
  valor_tipo: number;
  valor_estandar: number;
}

我想創建一個具有相同字段的數組,因為在對象CalculoEstadistico我可以接收到很多信息,並且需要CalculoEstadistico任何寄存器的“標頭”,如下所示:

export interface AreaEstadistica2 {
  id_area_estadistica: String; //Header from this
  nombre: String;
  id_distrito: String;// To this
  uso: string;      
  valor_tipo: number;
  valor_estandar: number;
}

Angular 5中的服務:

getAreasEstadisticas(): Observable<AreaEstadistica[]> {
    let url: string = this.urlEstadisticas;   
    console.log('URL' + url);
    return this._http.get<AreaEstadistica[]>(url);
  }

我通過在組件中使用map進行了嘗試:

    areas: AreaEstadistica[] = [];
    areas2: AreaEstadistica2[] = [];
//...

getAreas() {
    this._EstadisticasService
      .getAreasEstadisticas()
      .subscribe(
        res => {
          this.areas = res;
          this.transformArray();
        },
        err => {
          console.log(err);
          alert('error');
        }
      );
  }
transformArray(){
    this.areas.map(item => {
            return {
               id_area_estadistica: item.id_area_estadistica,
               nombre: item.nombre,           
               id_distrito: item.id_distrito,
               aa_ponencia_total: item.aa_ponencia_total,
               uso: item.calculos_estadisticos_pt[i].uso,                    
               valor_estandar: item.calculos_estadisticos_pt[i].valor_estandar,
               valor_tipo: item.calculos_estadisticos_pt[i].valor_tipo
            };
        }).forEach(item => this.areas2.push(item));
}

但是此代碼不起作用。 錯誤之一:

src / app / estadisticas / estadisticas.component.ts(129,57):錯誤TS2304:找不到名稱“ i”。

有任何想法嗎? 我不知道如何訪問對象CalculoEstadistico的字段來映射它們:

uso: item.calculos_estadisticos_pt[i].uso,                    
valor_estandar: item.calculos_estadisticos_pt[i].valor_estandar,
valor_tipo: item.calculos_estadisticos_pt[i].valor_tipo

有沒有辦法將嵌套的模型數組復制到另一個模型數組? 謝謝!

您使用不存在的索引i

valor_tipo: item.calculos_estadisticos_pt[i].valor_tipo

看起來您想在主數組中添加嵌套數組的字段。 例如

arry1 = {
  name: 'suhel',
  id: 1,
  contact : {
    email: 'email',
    number: '123'
  }
}

現在像這樣迭代嵌套數組

for(let key of Object.keys(arry1.contact)) {
  arry1[key] = arry1.contact[key];
}

現在,如果需要,請刪除聯系人字段

delete arry1["contact"];

那么最終結果將是這樣

arry1 = {
  email: "email"
  id: 1
  name: "suhel"
  number: "123"
}

暫無
暫無

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

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