简体   繁体   English

如何在Angular JS的对象数组内求和货币值

[英]How to sum up currency values inside an array of objects in Angular JS

I have a return array of objects from a API call . 我有一个API调用返回的对象数组。 And the object structure looks something like this .. 对象结构看起来像这样..

在此处输入图片说明

Like this the array can contain n number of Objects. 像这样,数组可以包含n个对象。

What I have to do is .. sum up all the values of all the object's selectedMapping.cost and display the sum. 我要做的是.. sum up all the values of all the object's selectedMapping.cost并显示总和。

But one problem is that the costs can be a bit tricky. 但是一个问题是costs可能有些棘手。

They can be in format like .30 or 978. etc etc for which we have to assume 0.30 and 978.00 respectively. 它们可以采用.30或978等格式,因此我们必须分别假设0.30和978.00。 They can be null or undefined also in which case we have to default it to 0.0 它们也可以为null或未定义,在这种情况下,我们必须将其默认设置为0.0

How can I achieve the sum in Angular JS ? 如何在Angular JS中实现总和? How to handle the appropriate conversions and display the sum ? 如何处理适当的转换并显示总和?

This seems like a good time to use reduce 这似乎是使用减少的好时机

 const data = [ { selectedMapping: { cost: ".30" } }, { selectedMapping: { cost: "200" } }, { selectedMapping: { cost: ".60" } }, { selectedMapping: { cost: ".22" } }, { selectedMapping: { cost: null } }]; const sumCost = (data) => data.reduce( (cost, entry) => cost + (parseFloat(entry.selectedMapping.cost) || 0), 0 ) console.log(sumCost(data)) 

Hope I got you right, then this plunker I have created should do what you want: https://embed.plnkr.co/zzQkybjND5xi2Uo7dNHZ/ 希望我对你没错,然后我创建的这个插件可以满足您的要求: https ://embed.plnkr.co/zzQkybjND5xi2Uo7dNHZ/

Simply iterate over the array, check the value for null or undefined if so set it to 0.0 and sum all values. 只需遍历数组,检查该值是否为null或undefined(如果将其设置为0.0)并求和所有值。

Here's my solution which handles undefined/null items 这是我处理未定义/空项目的解决方案

const sum = items.reduce((prevVal,item)=>{
  const selectedMapping = item.selectedMapping || null
  const cost = (isNaN(selectedMapping) && 'cost' in selectedMapping)? Number(selectedMapping.cost) : 0 
  return prevVal + cost
},0)
console.log(sum.toFixed(2))

Here's a JSBin for it 这是一个JSBin

And reference for JavaScript's Map, Reduce, and Filter 以及JavaScript的Map,Reduce和Filter的参考

you could map over the array and get the cost and then use R.sum method of ramdajs 您可以映射到数组并获取成本,然后使用ramdajs的R.sum方法

const array = [
  {
    selectedMapping: {
      cost: ".30"
    }
  },
  {
    selectedMapping: {
      cost: "200"
    }
  },
  {
    selectedMapping: {
      cost: ".60"
    }
  },
  {
    selectedMapping: {
      cost: ".10"
    }
  },];

const currency = array.map(curr=>parseFloat(curr.selectedMapping.cost))
R.sum(currency); 

here is the code repel to do that. 是拒绝执行操作的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM