如何减少字符串价格的对象数组

how to reduce an array of objects of stringed price

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

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

抱歉,如果这个类似的问题已经发布在其他地方,但我仍在学习如何在此处导航,而且我还没有找到类似的情况,除非有人可以指出我!

在代码中,您当前使用的 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>

在这里,我使用了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)