如何使用JS获得不同的值并在JSON上求和 [英] How to get distinct values and sum the total on JSON using JS

查看:257
本文介绍了如何使用JS获得不同的值并在JSON上求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何从不同的值中获取数据,也要对同一唯一行中的总值求和

How do you get the data from distinct values also sum the total values from the same unique row

这是JSON数据结果

如您所见,它们具有相同的全名.在总和priceGross的同时,如何获得不同的值.

As you can see they have the same full name. How do you get the distinct value while sum the total priceGross.

结果应该返回 例如. "Khalem Williams"并添加总计priceGross " 1200 + 1200 " = 2400

The result should be returning eg. "Khalem Williams" and adding the total priceGross " 1200 + 1200 " = 2400

结果回报

FullName : "Khalem Williams" 
TotalPriceGross: "2400"

我在下面的代码中获得了不同的值,但是我想知道如何将总priceGross求和,同时也获得不同的值.

I'm getting the distinct values with the code below but I'm wondering how to sum the total priceGross while also getting the distinct values.

var countTotal = [];

$.each(data.aaData.data,function(index, value){
          if ($.inArray(value.invoiceToFullName, countTotal)==-1) {
                    countTotal.push(value.invoiceToFullName);
          }
});

推荐答案

老实说,我建议您将数据转换为名称为键(唯一)且总价格为值的对象:

I would honestly suggest converting your data to an object with names as keys (unique) and total gross prices as values:

{
  "Khalem Williams": 2400,
  "John Doe": 2100
}

但是,我在下面的示例代码中包含了有关如何将数据也转换为对象数组的示例代码.我使用了Object.keysArray#reduceArray#map的组合.

However, I have included in the snippet below example code for how to convert your data to an array of objects as well. I used a combination of Object.keys, Array#reduce and Array#map.

var data = {
  aaData: {
    data: [{
        invoiceToFullName: "Khalem Williams",
        priceGross: 1200
      },
      {
        invoiceToFullName: "Khalem Williams",
        priceGross: 1200
      },
      {
        invoiceToFullName: "John Doe",
        priceGross: 500
      },
      {
        invoiceToFullName: "John Doe",
        priceGross: 1600
      },
    ]
  }
}

var map = data.aaData.data.reduce(function(map, invoice) {
  var name = invoice.invoiceToFullName
  var price = +invoice.priceGross
  map[name] = (map[name] || 0) + price
  return map
}, {})

console.log(map)

var array = Object.keys(map).map(function(name) {
  return {
    fullName: name,
    totalPriceGross: map[name]
  }
})

console.log(array)

这篇关于如何使用JS获得不同的值并在JSON上求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆