【问题标题】:how to reduce an array of objects of stringed price如何减少字符串价格的对象数组
【发布时间】:2022-01-01 18:10:12
【问题描述】:
var groceries = [
  {
    id: 1,
    product: 'Olive Oil',
    price: '$' + 12.1
  },
  {
    id: 2,
    product: 'Tomato Soup',
    price: '$' + 3.48
  },
  {
    id: 3,
    product: 'Cheesecake',
    price: '$' + 17.36
  },
  {
    id: 4,
    product: 'Sirloin Steak',
    price: '$' + 14.8
  },
  {
    id: 5,
    product: 'Brie Cheese',
    price: '$' + 23.28
  }
];

var sum = _.reduce(products, function (total, price) {
    return total + price;
  }, 0);

在我们开始添加价值之前,我不太确定如何从价格中删除“$”。我已经尽力在这里寻找其他解决方案(我是新手),但似乎只有“价格”只是数字的例子。

对不起,如果这个类似的问题已经在其他地方发布了,但我仍在学习如何在这里导航,除非有人能指出我,否则我还没有找到类似的情况!

【问题讨论】:

  • 一种方法是return total + parseFloat(price.slice(1));,但正如后来的 cmets 建议的那样,存储货币并不是最好的举措。只需存储数字,稍后添加货币即可显示。
  • 您可以控制groceries 数据吗?如果是这样,您能否向仅包含原始价格数字值的对象添加另一个属性(例如 priceNumber: 21.1
  • 为什么不存储没有货币符号的价格。如有必要,将其存储在不同的属性中。
  • @NickParsons 不幸的是,我无法控制数据..

标签: javascript string integer reduce


【解决方案1】:

在代码中,您当前使用的price 是具有数组属性的每次迭代的对象。相反,您可以从对象中获取价格属性。

在您的示例数据中,只有前导 $ 可以从价格属性中删除。然后您可以使用例如 parseFloat 并仅在转换未产生 NaN 时添加该值。

然后将groceries 变量传递给reduce,而不是示例代码中不存在的products

请注意,目前我们正在添加相同货币的值,如果您使用不同的货币,则在计算总和时必须考虑到这一点。

var groceries=[{id:1,product:'Olive Oil',price:'$'+12.1},{id:2,product:'Tomato Soup',price:'$'+3.48},{id:3,product:'Cheesecake',price:'$'+17.36},{id:4,product:'Sirloin Steak',price:'$'+14.8},{id:5,product:'Brie Cheese',price:'$'+23.28},{id:6,product:'Product with invalid price',price:'$'+"hello"}];

var sum = _.reduce(groceries, function (total, obj) {
  var price = parseFloat(obj.price.replace(/^\$/, ''));
  if (!isNaN(price)) {
    return total + price;  
  }
  return total;
}, 0);

console.log(sum)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script>

【讨论】:

    【解决方案2】:

    这里,我使用了 Javascript 的默认函数 reduce 来获取累计和。

    var groceries = [
      {
        id: 1,
        product: 'Olive Oil',
        price: '$' + 12.1
      },
      {
        id: 2,
        product: 'Tomato Soup',
        price: '$' + 3.48
      },
      {
        id: 3,
        product: 'Cheesecake',
        price: '$' + 17.36
      },
      {
        id: 4,
        product: 'Sirloin Steak',
        price: '$' + 14.8
      },
      {
        id: 5,
        product: 'Brie Cheese',
        price: '$' + 23.28
      }
    ];
    
    //reduce((total, currentIteratedValue) => {}, initialCumulativeValue)
    //Initially we take sum as 0
    const sum = groceries.reduce(function (currentTotal, obj) {
      var price = parseFloat(obj.price.slice(1));
      if (!isNaN(price)) return currentTotal + price;  
      return currentTotal;
    }, 0);
    
    
    console.log(sum)

    【讨论】:

    • 这成功了!太感谢了。我误解了迭代器部分..
    猜你喜欢
    • 2021-10-25
    • 2014-11-15
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 2023-01-20
    • 2021-12-07
    相关资源
    最近更新 更多