【问题标题】:Javascript: How to use Reduce to get New Array of ObjectsJavascript:如何使用 Reduce 获取新的对象数组
【发布时间】:2018-12-07 00:02:36
【问题描述】:

我是编码新手,所以这可能是一个简单的问题,但我无法理解。我有一系列最好的馅饼,每个都有自己的价格:

pieArr = [blueberry, strawberry, pumpkin, apple]

我想创建一个对象数组,根据馅饼的价格显示购物车的总数,这里有人在堆栈溢出时建议我使用 reduce。

这是我目前所拥有的:

var total = 0;

const totalArr = pieArr.reduce((totalPrice, pie) => {
  if ( pie === "blueberry") {
    total += 2.5;
    totalPrice.push({["cartTotal"]:total});
    return totalPrice;
  }
 else if (pie === "apple") {
   total += 2;
   totalPrice.push({["cartTotal"]:total});
   return totalPrice;
 }, 
 [])};

我希望最终结果是一个不断添加新总数的新对象数组:

[{cartTotal:2.5},{cartTotal:4.5}]

创建了新的对象数组,但总和没有相加,所以两次总为 0:

[{cartTotal: 0},{cartTotal: 0}]

我做错了什么?

【问题讨论】:

  • const total = 0; 呃,const,你确定? const total = total + 2.5; 也是无效的语法,我认为代码不应该首先运行? (另外,当第一个 if 条件也满足时,您可能想要 return totalPrice
  • const total = total + 2.5; 中,您同时声明和读取变量。请注意,外部const total = 0; 在这里被遮盖了。你真的是想const-声明这个吗? else if} 在哪里?您确定在这两种情况下都返回一个值吗?
  • 哦,好的,所以我修复了 const 总数,并将 return 添加到第一个 if 语句。但是,它仍然没有改变总数,还有其他想法吗?
  • 如果您要更改该变量,则不应使用const。并让totalreduce 操作之外定义。这样,在一次reduce操作迭代后,total不会被初始化。
  • 感谢CertainPerformance、Xufox 和@Meet Zaveri。我现在明白了如果我要更改变量,则不使用 const 是什么意思。当我将其更改为 var

标签: javascript arrays loops object


【解决方案1】:

一个很好的方法是进行价格查询,例如:

let piePrices = {
    blueberry: 2.25,
    strawberry: 1.5, 
    pumpkin: 3,
    apple: 2
}

然后你可以在map() 中使用它(如果你只是从一个数组中创建一个数组,它比reduce() 更好)而没有所有if/else 噪音:

let piePrices = {
    blueberry: 2.25,
    strawberry: 1.5, 
    pumpkin: 3,
    apple: 2
}

let pieArr = ['blueberry', 'strawberry', 'pumpkin', 'apple']

let total = 0
let totalPrice = pieArr.map(pie =>  ({cartTotal: total += piePrices[pie]}))

console.log(totalPrice)

【讨论】:

  • 标记你的结构很好。通过查找对象!
【解决方案2】:

const total = 0;
let pieArr = ['blueberry', 'strawberry', 'pumpkin', 'apple']
const totalArr = pieArr.reduce((totalPrice, pie) => {
  let foundPie = totalPrice.find(x => x.name === pie) || {name: pie, total: 0};
  
 if ( pie === "blueberry") {
    foundPie.total += 2.5;
 }
 else if (pie === "apple") {
   foundPie.total += 2;
 }
 
 if(!totalPrice.some(x=>x.name === pie)){
   totalPrice.push(foundPie)
 }
  return totalPrice;
}, []);

console.log(totalArr)

我建议添加另一个属性name 以获得更清晰的图片。当我们reducing时,从累积的totalPrice数组中找到饼图,然后求和,并检查是否将元素推入累积数组

【讨论】:

    猜你喜欢
    • 2018-12-16
    • 2021-10-10
    • 2019-11-09
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2017-02-17
    • 2020-08-27
    • 2021-12-02
    相关资源
    最近更新 更多