简体   繁体   English

如何转换嵌套在 Object 中的数组?

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

I'm stuck with compile errors while trying to to convert an Object that contains an Array of Objects.我在尝试转换包含对象数组的 Object 时遇到编译错误。

That's what's coming in:这就是即将到来的:

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

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

The output shall be typed objects (interfaces) I have left out many properties here for better reading, hence the "Course" object would look the same as the "CourseRaw" object except for the type "Image[]". output 应该是类型化的对象(接口)我在这里省略了许多属性以便更好地阅读,因此“Course”object 看起来与“CourseRaw”ZA8CFDE6331BD59EB.66AC96F891ZC4 之外的“CourseRaw”相同。 Notice that "Image" contains "uploaded" as Date rather than string as seen in "ImageRaw"请注意,“Image”包含“uploaded”作为日期,而不是“ImageRaw”中看到的字符串

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

In the transforming function I tried to copy the data into a new array, which the compiler doesn't accept:在转换 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
    };
  }

My attempt to actually copy the data (failed):我尝试实际复制数据(失败):

   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;
  }

How can I make it right?我怎样才能使它正确?

You should type the Image return array.您应该键入Image返回数组。 Furthermore you can add a map to to do it easily.此外,您可以添加 map 来轻松完成。

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

Since array creation is in the return instruction, TS should get the typings right.由于数组创建在返回指令中,TS 应该正确输入。

About your code:关于您的代码:

  1. You can make it work adding var newImages: Image[] = [];您可以添加var newImages: Image[] = []; (initialization and type definition) (初始化和类型定义)
  2. You should use push to add new items to the array;您应该使用push将新项目添加到数组中; if you really want to initialize array length (see related question/answer ), you should add newImages.length = imageRaws.length .如果你真的想初始化数组长度(见相关问题/答案),你应该添加newImages.length = imageRaws.length

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM