arrays - 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'
}
}
}
...那么类型类是...?
我尝试了一些非常有创意的、无效的尝试来让这个工作无济于事。我也希望我能理解如何处理这个非数组数组(没有方括号)。抱歉,如果这是重复的。
解决方案
在第二种情况下,您的things
类型将是这样的索引类型:
interface ThingHolder {
[key: string]: Thing;
}
这表示键是字符串,值是Thing
s。
的接口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 操场上的实时示例。
推荐阅读
- php - 为什么我不能在这段代码中使用 jQuery 在 HTML 中添加一行?
- javascript - Javascript视频播放器不加载随机选择的视频
- kubernetes - 为集群中的单个 pod 设置环境变量
- react-native - 登录/注册页面中的 TextInput 自动失去焦点
- asp.net - 在 Asp.Net MVC 中的 Datatables 中获取用于排序的多个列的名称
- mysql - Powershell - mySQL 查询,每隔一次运行出错
- flutter - Flutter:加载本地json文件返回null
- spring-mvc - 编译器在运行我的第一个控制器方法后排除错误
- javascript - Vue路由器不匹配具有多个动态值的url
- html - 如何将按钮标签放在左侧,将图标放在右侧?