首页 > 解决方案 > Angular:你如何识别带有 id 的 JSON 对象?

问题描述

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

我所理解的

如果这是我的对象:

{ 
     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'
         }
     }
 }

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

我尝试了一些非常有创意的、无效的尝试来让这个工作无济于事。我也希望我能理解如何处理这个非数组数组(没有方括号)。抱歉,如果这是重复的。

标签: arraysjsonangularobject

解决方案


在第二种情况下,您的things类型将是这样的索引类型

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

TypeScript 操场上的实时示例。


推荐阅读