簡體   English   中英

如何轉換嵌套在 Object 中的數組?

[英]How to transform an Array nested in an Object?

我在嘗試轉換包含對象數組的 Object 時遇到編譯錯誤。

這就是即將到來的:

export interface CourseRaw {
  metaInfo: MetaInfoRaw;
  gameCode: number;
  gameText: string;
  images?: ImageRaw[]; // Problems here
}

export interface ImageRaw {
  uploaded: string;
  url?: string;
  description?: string;
  fileName?: string;
}

output 應該是類型化的對象(接口)我在這里省略了許多屬性以便更好地閱讀,因此“Course”object 看起來與“CourseRaw”ZA8CFDE6331BD59EB.66AC96F891ZC4 之外的“CourseRaw”相同。 請注意,“Image”包含“uploaded”作為日期,而不是“ImageRaw”中看到的字符串

export interface Image {
  uploaded: Date;
  url?: string;
  description?: string;
  fileName?: string;
}

在轉換 function 中,我嘗試將數據復制到編譯器不接受的新數組中:

export class CourseFactory {    
  static fromRaw(courseRaw: CourseRaw): Course {
    return {
      ...courseRaw,      
      ratingInfo: RatingFactory.fromRaw(courseRaw.ratingInfo), // demo of another nested object (works)
      images: ImageFactory.fromRaw(courseRaw.images) // problematic call
    };
  }

我嘗試實際復制數據(失敗):

   static fromRaw(imageRaw: ImageRaw[]): Image[] {
    var newImages;

    var i;
    for (i = 0; i < imageRaw.length; i++) {
      newImages[i].uploaded = new Date(imageRaw[i].uploaded);
      newImages[i].url = imageRaw[i].url;
      newImages[i].description = imageRaw[i].description;
      newImages[i].fileName = imageRaw[i].fileName;
    }
    return newImages;
  }

我怎樣才能使它正確?

您應該鍵入Image返回數組。 此外,您可以添加 map 來輕松完成。

static fromRaw(imageRaws: ImageRaw[]): Image[] {
  return imageRaws.map(raw => {
    return {
      uploaded: new Date(...),
      url: raw.url,
      // etc.
    }
  });
}

由於數組創建在返回指令中,TS 應該正確輸入。

關於您的代碼:

  1. 您可以添加var newImages: Image[] = []; (初始化和類型定義)
  2. 您應該使用push將新項目添加到數組中; 如果你真的想初始化數組長度(見相關問題/答案),你應該添加newImages.length = imageRaws.length

暫無
暫無

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

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