我正在嘗試從后端服務讀取產品并將其顯示在angular前端。我已經宣告了一系列產品,其中包含翻譯所需的密鑰。我根據后端服務回傳的代碼進行匹配 代碼有效,但是我認為這不是一種有效的方法,因為我使用了兩個 for 回圈。有人可以提出更好的方法嗎
products: Choice[];
products1: Choice[] = [
{ label: 'common.base-metal', value: 'BASESPECIALITY' },
{ label: 'common.crop-nutrient', value: 'CROPNUTRIENT' },
{ label: 'common.iron-ore', value: 'IRONORE' },
{ label: 'common.metal-coal', value: 'METCOAL' },
{ label: 'common.precious-metals', value: 'PRECIOUS' },
{ label: 'common.shipping', value: 'SHIPPING' },
{ label: 'common.thermal-coal', value: 'THERMALCOAL' },
{ label: 'legal-forms.OTHER', value: 'other' }
];
this.referenceStore
.getReference('products')
.pipe(
first(),
tap((products) => {
products.forEach((pro) =>{
this.products1.forEach((pro1) =>{
if(pro.code === pro1.value){
pro.name = pro1.label;
}
});
});
this.products = products.map((product) => ({ label: product.name, value: product.code }));;
this.products.push({ label: 'Other', value: 'other' });
})
)
.subscribe();
uj5u.com熱心網友回復:
這是一個簡單的代碼,只需要一個回圈,而不是嵌套 forEach 回圈,你可以試試這個。
let products1Map = {}
this.products1.forEach((pro1) => {
products1Map[pro1.value] = pro1.name;
});
this.products = products.map((product) => ({
label: products1Map[product.code] ? products1Map[product.code] : product.name,
value: product.code
}));;
this.products.push({
label: 'Other',
value: 'other'
});
})
uj5u.com熱心網友回復:
你考慮過使用 Map 嗎?
https://howtodoinjava.com/typescript/maps/
products1: Map<string, string> = new Map([
['BASESPECIALITY', 'common.base-metal'].....
]);
this.referenceStore
.getReference('products')
.pipe(
first(),
tap((products) => {
this.products = products.map((product) => ({ label: products1.get(product.code), value: product.code }));
this.products.push({ label: 'Other', value: 'other' });
})
)
.subscribe();
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/326545.html
下一篇:禁用angular2多選復選框
