这是两个对象:
const discount = {
rate: 0.50,
reason: 'New Year Sales'
}
const products = [
{
name: 'TV',
price: '1200'
},
{
name: 'Bed',
price: '500'
},
{
name: 'Table',
price: '50'
}
]
我想将它们放入新对象中
const newProducts = [
{
name: 'TV',
price: '1200',
rate: 0.50,
reason: 'New Year Sales',
finalPrice: 600
},
{
name: 'Bed',
price: '500',
rate: 0.50,
reason: 'New Year Sales',
finalPrice: 250
},
{
name: 'Table',
price: '50',
rate: 0.50,
reason: 'New Year Sales',
finalPrice: 25
}
]
这是一个JavaScript练习,我已经尝试过'Object.assign',但是新值将覆盖旧值,导致仅提供最新的值。我不确定使用{... products}和map,forEach进行销毁是否会有用。我无法做到这一点
答案 0 :(得分:0)
因此,您想遍历products
中的每个产品,并将discount
应用于每个产品吗?
使用.map
通过遍历products
中的每个项目并对其应用回调函数来创建新数组:
const newProducts = products.map(oldProduct=>{
return {
name: oldProduct.name,
price: oldProduct.price,
rate: discount.rate,
reason: discount.reason,
finalPrice: (discount.rate * oldProduct.price)
}
})
注意:就我个人而言,我更喜欢它而不破坏结构,因为我认为它的读起来更加清晰。但是,销毁当然可以。
答案 1 :(得分:0)
使用Array#map,destructuring和spread syntax。
const discount={rate:0.50,reason:'New Year Sales'}
const products=[{name:'TV',price:'1200'},{name:'Bed',price:'500'},{name:'Table',price:'50'}]
const {rate} = discount;
const res = products.map(({price, ...rest})=>{
return {...rest, ...discount, price, finalPrice: rate*price}
});
console.log(res);
答案 2 :(得分:0)
您可以将一个空的对象分配给映射的产品,折扣和最终价格。
const
discount = { rate: 0.50, reason: 'New Year Sales' },
products = [{ name: 'TV', price: '1200' }, { name: 'Bed', price: '500' }, { name: 'Table', price: '50' }],
newProducts = products.map(product => Object.assign(
{},
product,
discount,
{ finalPrice: product.price * (1 - discount.rate) }
));
console.log(newProducts);
.as-console-wrapper { max-height: 100% !important; top: 0; }