简体   繁体   中英

Typescript dynamically generate variable name

I need to dynamically create variable instances and assign values in single statement as below.

this.myList1[data.id] = data.id + "-" + data.desc;
this.myList2[data.id] = data.id + "-" + data.desc;
this.myList3[data.id] = data.id + "-" + data.desc;
this.myList4[data.id] = data.id + "-" + data.desc;
this.myList5[data.id] = data.id + "-" + data.desc;
this.myList6[data.id] = data.id + "-" + data.desc;

Can someone suggest me what is the best way to do this in Typescript?

Use template string literals and bracket notation syntax with this :

myList.forEach((data: object, index: number) => {
    this[`myList${index + 1}`][data.id] = `${data.id}-${data.desc}`;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM