In my coding project, I am dealing with an empty array, a value, and an object. Since there are multiple objects involved, I want to organize them into categories. Here is an example of what I envision:
ARRAY
KEY
OBJECT
OBJECT
KEY
OBJECT
Initially, the array is empty as shown below:
public serviceTable: Services[] = [];
This is the interface for the array objects:
export interface Services {
details:
{
service: string,
description: string
}
}
The object I receive from result
looks like this:
data: {
details: [
{
service: this.formMain.get('service')?.value,
description: this.formMain.get('description')?.value
}
]
}
Lastly, here is how I try to define the dynamic key for the array and its objects:
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()
}
}
While the if-statement works fine, I encounter an issue with the else-statement leading to the error:
TS2339: Property 'push' does not exist on type 'Services'.
The error possibly occurs because
this.serviceTable[this.randomNumber]
is not recognized as an array.
If the key (this.randomNumber
) doesn't already exist in the array, it will be created. However, if it does exist, I intend to add the new object under the same key.
Hence, I aim to iterate through the array and access all objects associated with a specific key, like this:
for (let item of this.serviceTable[3]) { // The number can also be replaced by a string, e.g., this.serviceTable['myCategory']
console.log(item.service); // This should display all services linked to the key '3'
}
How can I achieve this functionality?
Check out an example of my code on StackBlitz.