I have an empty array, a value and an object. Since I have many objects, I would like to categorize them. Somehow like this:
ARRAY
KEY
OBJECT
OBJECT
KEY
OBJECT
This is the array, which is empty by default:
public serviceTable: Services[] = [];
This is its interface:
export interface Services {
details:
{
service: string,
description: string
}
}
This is the object that I get from result:
data: {
details: [
{
service: this.formMain.get('service')?.value,
description: this.formMain.get('description')?.value
}
]
}
And last but not least, this is how I try to define the dynamic key of that array and its object.
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()
}
}
The if-statement works good but there is something wrong with else-statement since I get this error:
TS2339: Property 'push' does not exist on type 'Services'.
I probably get this error because this.serviceTable[this.randomNumber] is not an array.
So if the key (this.randomNumber) does not exist in the array, it will be created. But if it already exists, I want to add the new object into the same key.
So my goal is to loop the array and call all objects that belong to a specific key, somehow like this:
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'
}
How can I do this?
See an example of my code on StackBlitz OR see the full code on BitBucket.
from Pushing objects into dynamic keys
No comments:
Post a Comment