How to reformat the array of object as simplest way and push to formGroup as below. How I can avoid using product word repeatly? Eg: spread operators
for (const product of products) {
this.productArray.push(
this.fb.group({
// How to simplify this code
id: product.product_id,
name: product.product_name,
chargers: product.sales_chargers,
class: product.class_name,
price: product.price,
}),
);
}
CodePudding user response:
I don't see formulaic transform from the OP's product keys to the OP's group keys. One alternative is to capture the transformation in data. Then at least, you can define the mapping clearly and know where to go to edit it...
const keyMap = { product_id: 'id', product_name: 'name', sales_chargers: 'chargers', class_name: 'class', price: 'price' };
const product2Group = product => Object.fromEntries(
Object.entries(product).map(([k, v]) => [ keyMap[k] , v ])
);
Then, we can replace the OP loop with...
this.productArray = products.map(product2Group);
Demo...
const keyMap = {
product_id: 'id',
product_name: 'name',
sales_chargers: 'chargers',
class_name: 'class',
price: 'price'
};
const product2Group = product => Object.fromEntries(
Object.entries(product).map(([k, v]) => [ keyMap[k] , v ])
);
const products = [
{ product_id: 4, product_name: 'my product four', sales_chargers: 'chargers 4', class_name: 'classy class 4', price: 44 },
{ product_id: 5, product_name: 'my product five', sales_chargers: 'chargers 5', class_name: 'classy class 5', price: 55 }
]
const result = products.map(product2Group);
console.log(result);
CodePudding user response:
You cannot access a property, without mentioning the reference. Any solution without product
is more complicated than Your code.
However you might want to use .map
to convert each item of the array in a more elegant way.
this.productArray = products.map(product =>
this.fb.group({
id: product.product_id,
name: product.product_name,
chargers: product.sales_chargers,
class: product.class_name,
price: product.price,
})
)