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

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

问题描述

如何从不同的值中获取数据并将同一行的总值相加

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

这里是 JSON 数据结果

Here is the JSON Data result

如您所见,它们具有相同的全名.您如何在求和总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天全站免登陆