【问题标题】:How do I create a new Object that has 2 or more Objects' properties that have different sizes and set up a new property如何创建具有 2 个或多个具有不同大小的对象属性的新对象并设置新属性
【发布时间】:2019-06-14 22:45:53
【问题描述】:

这是两个对象:

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

【问题讨论】:

标签: javascript json


【解决方案1】:

所以你想遍历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)
  }
})

注意:就我个人而言,我更喜欢不解构,因为我认为它读起来更清晰。但解构确实有效。

【讨论】:

  • 注意这会改变原始数组,你可以这样做 -> return { rate: discount.rate, reason: discount.reason.....etc
  • I prefer it without destructuring 传播/解构是我最喜欢的,但这里的所有 3 个答案都很好。您的一个优势是,它可以与更多浏览器一起使用,而无需使用转译器。它们甚至可能是速度优势..
  • 不用解构,这绝对是最简单的读法~TQ
【解决方案2】:

使用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);

【讨论】:

  • 你确定是对的,我需要一段时间来学习,因为我还是新手,所以需要一些时间来消化解构部分。
  • @ChaiChongTeh,是的,这需要一些时间来理解,但是一旦你理解了它就很容易阅读,你真的可以做出一些很酷的工作算法。
【解决方案3】:

您可以取一个空对象并分配产品、折扣和最终价格以进行映射。

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; }

【讨论】:

  • 为什么要使用Object.assign 而不仅仅是在新对象上声明属性?
  • 因为 op 想尝试一下。我发现它比声明新道具更好。
  • 感谢您对 Object.assign 的帮助,我还是新手。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多