How to get single values ​​and sum total in JSON using JS

As you get data from different values, also sum the total values ​​from the same unique row

Here is the result of JSON Data p>

enter image description here

As you can see, they have the same full name. How do you get a clear value, and summarize the totals priceGross.

The result should be returned for example. "Khalem Williams"and adding the general meaningpriceGross " 1200 + 1200 " = 2400

return return

FullName : "Khalem Williams" 
TotalPriceGross: "2400"

I get different values ​​using the code below, but I am wondering how to sum the total price of Gross, and also get different values.

var countTotal = [];

$.each(data.aaData.data,function(index, value){
          if ($.inArray(value.invoiceToFullName, countTotal)==-1) {
                    countTotal.push(value.invoiceToFullName);
          }
});
+4
source share
2 answers

() :

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

, . Object.keys, Array#reduce 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)
Hide result
+2

, , , , json, , json.

sql.

:

   var resultsData = [{name: 'sipho', amount: 10}, {name: 'themba', amount: 30}, {name: 'sipho', amount: 60}, {name: 'naidoo', amount: 30}, {name: 'gupta', amount: 70}, {name: 'naidoo', amount: 10}];

(), :

var customers = $.unique(resultsData.map(function(value){return value.name}));

:

var desiredSummary = customers.map(function(customer){
    var sum =0; 
    $.each(test,function(index, value){sum+=(value.name==customer?value.amount:0)}); 
    return {customer: customer, sum: sum}
});

, ,

+1

Source: https://habr.com/ru/post/1671414/


All Articles