如何创建具有2个或多个具有不同大小的对象属性的新对象并设置一个新属性

时间:2019-01-21 14:11:13

标签: javascript json

这是两个对象:

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进行销毁是否会有用。我无法做到这一点

3 个答案:

答案 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#mapdestructuringspread 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; }