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')

>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

Leave a Reply