【问题标题】:How can I map an object with index signature?如何使用索引签名映射对象?
【发布时间】:2019-09-17 13:01:47
【问题描述】:

我即将用 Angular 编写一个应用程序。它从 api 接收答案。这个答案里面是一个用字符串索引的数组(索引签名)。如何将此数组映射到常规数组?

api 是这样的

{
    "Information": {
        "Created": "2019-04-25",
        "Version": "1.2"
    },
    "Files": {
        "2019-04-26": {
           'name': 'file1',
           'size': 5,
        },
        "2019-04-25": {
            'name': 'file2',
            'size': 3,
        },
    ...
        }
    }

我想把它映射成一个像这样的对象

export class Model {
  'Information': {
    'Created': string,
    'Version': string,
  };
  'Files': [{ 
    'date': Date,
    'name': string,
    'size': number,
  }];
}

这里我要映射答案

getdata(url): void {
      this.http.get<>(url).subscribe(data => {
        // code
        }
      );
  }

【问题讨论】:

    标签: json angular typescript api


    【解决方案1】:

    我没有对此进行任何测试,但总而言之,for 循环检索对象 data.File 的所有键,您可以通过该键访问该对象。

    getdata(url): void {
      this.http.get<>(url).subscribe((response: any) => {
        const model: Model = new Model();
        model.Files = [];
    
        if (response.Information) {
          const information: any = response.Information;
          if (information.Created && information.Version) {
            model.Information = {
              'Created': information.Created,
              'Version': information.Version
            };
          }
        }
    
        for (const date in data) {
          if (data.File.hasOwnProperty(date)) {
            const file: any = data.File[date];
            model.Files.push({
              'date': date,
              'name': file.name,
              'size': file.size
            });
          } 
        }
      });
    }
    

    【讨论】:

      【解决方案2】:
      Object.keys(o.Files)
        .map(function(k ) {
          return {date: k, name: o.Files[k].name, size: o.Files[k].size}
        });
      

      【讨论】:

        【解决方案3】:

        应该是这样的:

        data: Array<Data>;
            
        getData() {
          this.http.get(`url`).subscribe((data) => {
             this.data = data.map(item => {
              const output = {};
              output.information = item.information;
              output.files = Object.keys(item.files).map(key => {
                return {
                  date: new Date(key),
                  name: item.files[key].name,
                  size: item.files[key].size
                };
              });
              return output;
             });
          });
        }

        【讨论】:

          猜你喜欢
          • 2018-12-30
          • 2018-05-07
          • 2023-03-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-04
          • 2021-04-13
          • 2021-03-06
          相关资源
          最近更新 更多