I have the following JSON object assigned to allDepartments, which is an array of a custom datatype contactItem:
export interface contactItem {
id : number;
position: string;
name : string;
email : string;
extension : number;
phone : Text;
department: string;
}
public allDepartments: contactItem[];//interface defined in conatctService
This is allDepartmnets:
:
[
{
"id": "1",
"position": "Director of Pathology and Laboratory Medicine",
"name": "Dr. Niall Swan",
"email": "[email protected]",
"extension": "4798",
"phone": "012214798",
"department": "General"
},
{
"id": "2",
"position": "Laboratory Manager",
"name": "Donal Murphy",
"email": "[email protected]",
"extension": "4510",
"phone": "012124510",
"department": "General"
},
{
"id": "4",
"position": "Laboratory Manager",
"name": "Donal Murphy",
"email": "[email protected]",
"extension": "4510",
"phone": "012124510",
"department": "General"
},....
When the department key is equal to biochemistry in an contactItem I want to add the contactItem object to an array of contactItems called biochemistry :
public biochemistry : contactItem[];
//itearte array and assign biochemistry contacts
console.log("contacts.page.ts: trting to get biohemistry data...");
for (var contact in this.allDepartments){
console.log("contact = " + this.allDepartments[contact].department);
if (this.allDepartments[contact].department="biochemistry"){
this.biochemistry.push(this.allDepartments[contact]);
console.log("biochem object: " +this.allDepartments[contact]);//array of objects
}
}
})
However an exception is thrown :
TypeError: undefined is not an object (evaluating 'this.biochemistry.push'
The syntax for pushing an object to a Typescript array seems ok, so not sure what the issue is. Any input appreciated.
public biochemistry : contactItem[];is wrong, and that you're ignoring some TS warnings, but there isn't enough context in the question to see where you're expecting that property to be defined on the instancefor...into iterate the array more so because you don't use the index, just use afor...of. Second, you have a typo hereif (this.allDepartments[contact].department="biochemistry"){where you assign"biochemistry"to every department, you need double equals to check for equality(or better use triple equals):if (this.allDepartments[contact].department === "biochemistry"){.