javascript - How to set objects property not at the same place? -
i have model, lets say:
export interface car { driverid: string; drivername: string; color: string; }
in function want return an array of objects model, can build after few async calls happening in function, wanted declare empty array of model , assign relevant properties have them:
public getlistofcarobjects(): car[] { let listofcars: car[] = []; self._serviceone.getids().subscribe( (res: driversinfo) => { res.ids.map((id: string, idindex: number) => { listofcars[idindex].driverid = id; // more stuff api calls below , building object ... }
but im getting error:
error typeerror: cannot set property 'driverid' of undefined
how, should this?
thanks!!
you have create object instance @ index referencing. create when receive data, either pushing value or setting index:
listofcars.push({ driverid: id, dirvername: "", color: "" }); listofcars[idindex] = { driverid: id, dirvername: "", color: "" };
since interface specifies properties required have specify them when creating new object, did above. if create cars
anid can mark rest of properties optional:
export interface car { driverid: string; drivername?: string; color?: string; }
Comments
Post a Comment