Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Setting values in an array of objects

How would I add a value to agencyList[0].itemName?

export class SelectedItem {
 id: number;
 itemName: string;
 isChecked: boolean;
}

agencyList: SelectedItem[] = [];

I am attempting agencyList[0].itemName = 'agency1'; but getting the error: Cannot set properties of undefined (setting 'itemName')

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to initialize agencyList[0] with an instance of SelectedItem first like

agencyList[0] = new SelectedItem();
agencyList[0].itemName = "agency1";

Presumably you only want to do this in cases where the item has not been initialized already:

if (!agencyList[0]) {
    agencyList[0] = new SelectedItem();
}
agencyList[0].itemName = "agency1";

And you can use nullish coalescing assignment to collapse that into a single line of code:

(agencyList[0] ??= new SelectedItem()).itemName = 'agency1'

Playground link to code

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading