我有一个空的array,一个value和一个object.因为我有很多对象,所以我想对它们进行分类.某种程度上是这样的:
ARRAY
KEY
OBJECT
OBJECT
KEY
OBJECT
这是数组,默认为空:
public serviceTable: Services[] = [];
这是它的界面:
export interface Services {
details:
{
service: string,
description: string
}
}
这是我从result
得到的对象:
data: {
details: [
{
service: this.formMain.get('service')?.value,
description: this.formMain.get('description')?.value
}
]
}
最后但并非最不重要的一点是,我试图定义该数组及其对象的动态键.
dialogRef.afterClosed().subscribe(result => {
if (result) {
if (!Object.keys(this.serviceTable)[result.section]) {
// No section found, lets create it ...
this.serviceTable[this.randomNumber] = [result];
console.log(this.serviceTable, 'ServiceTable')
}
else {
this.serviceTable[this.randomNumber].push()
}
}
if语句工作正常,但else语句有问题,因为我遇到了以下错误:
TS2339:类型"Services"上不存在属性"push".
我可能会遇到这个错误,因为this.serviceTable[this.randomNumber]
不是array.
因此,如果数组中不存在键(this.randomNumber
),将创建它.但如果它已经存在,我想将新对象添加到同一个键中.
所以我的目标是循环数组并调用属于特定键的所有对象,某种程度上如下所示:
for (let item of this.serviceTable[3]) { // Instead of a number, it could also be a string. For instance, this.serviceTable['myCategory']
console.log(item.service); // This should list all 'services' that belong to the key '3'
}
我该怎么做?
请参阅StackBlitz上的代码示例.