【问题标题】:Angular: How do you identify JSON objects with id's?Angular:你如何识别带有 id 的 JSON 对象?
【发布时间】:2019-03-16 15:38:09
【问题描述】:

为了简化我的问题,我将其分解如下:

我所理解的

如果这是我的对象:

{ 
     things: [{
         'text': 'version'
         'short': 'v',
         'order': 1,
         'id': 'A'
     },{
         'text': 'update'
         'short': 'u',
         'order': 2,
         'id': 'B'
     }]
}

...那么这是我的类型类:

 export class Thing {
     text: string;
     short: string;
     order: number;
     id: string;
 }

我不明白的地方

如果这个是我的数据:

 { things: {
         'A': {
             'text': 'version'
             'short': 'v',
             'order': 1,
             'id': 'A'
         },
         'B': {
             'text': 'update'
             'short': 'u'
             'order': 2
             'id': 'B'
         }
     }
 }

...那么类型类是...?

我尝试了一些非常有创意但无效的尝试,但无济于事。我也希望我能理解如何处理这个非数组数组(没有方括号)。如有重复请见谅。

【问题讨论】:

  • JSON 是一种用于数据交换的文本符号(More here.) 如果您正在处理 JavaScript 源代码,而不是处理 string,那么您就不是在处理 JSON。

标签: arrays json angular object


【解决方案1】:

在第二种情况下,您的things 类型将是index type,如下所示:

interface ThingHolder {
    [key: string]: Thing;
}

也就是说键是字符串,值是Things。

data 的接口将具有该类型的 things 属性:

interface AppropriateNameHere {
  things: ThingHolder;
}

那么,编译器对此很满意:

const data : AppropriateNameHere = {
  things: {
    'A': {
      'text': 'version',
      'short': 'v',
      'order': 1,
      'id': 'A'
    },
    'B': {
      'text': 'update',
      'short': 'u',
      'order': 2,
      'id': 'B'
    }
  }
};

Live Example 在 TypeScript 操场上。

【讨论】:

  • 太棒了!非常感谢!
猜你喜欢
  • 2019-08-14
  • 1970-01-01
  • 2013-01-02
  • 2023-02-15
  • 2019-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多