I am trying to read the products from the backend service and display it in the angular front-end. I have declared an array of products1, which contains the keys that are needed for the translation. I am matching based on the code returned by the backend service The code works however I think its not an efficient way since I am using two for loops. Could somebody suggest a better approach
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();
CodePudding user response:
this is the simple code that will require only a single loop instead of nesting forEach loop you can try this.
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'
});
})
CodePudding user response:
Have you considered the use of a 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();