D
D
developerrr2015-10-21 10:57:58
JavaScript
developerrr, 2015-10-21 10:57:58

How to add and display data on a page with the same property?

There is data in the format:

[{'id':1, 'amount':123, 'currency' : 'CHF'},{'id':2, 'amount':321, 'currency' : 'USD'},{'id':3, 'amount':4324, 'currency' : 'UAH'},{'id':4, 'amount':45645, 'currency' : 'USD'},{'id':5, 'amount':8972, 'currency' : 'CHF'}]

I need to display this data on the page (without id, of course), but I need it differently:
123 CHF
321 USD
4324 UAH
45645 USD
8972 CHF

and output like this (that is, do not duplicate the same currency, but add and display the total amount):
9095 CHF
45966 USD
4324 UAH

Tell me, please, how to do it right.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Kravchenko, 2015-10-21
@developerrr

var arr = [{'id':1, 'amount':123, 'currency' : 'CHF'},{'id':2, 'amount':321, 'currency' : 'USD'},{'id':3, 'amount':4324, 'currency' : 'UAH'},{'id':4, 'amount':45645, 'currency' : 'USD'},{'id':5, 'amount':8972, 'currency' : 'CHF'}];
var result = {};
arr.forEach(function(item){
  if(!result.hasOwnProperty(item.currency))
    result[item.currency] = 0;
  result[item.currency] += item.amount;

});

console.log(result)
//Object {CHF: 9095, USD: 45966, UAH: 4324}

M
Mike, 2015-10-21
@Goodilla

I think you need to sort by properties. We create an array, for example, an associative one. Then, we proceed to JSON. To begin with, if this is not an object, we form an object, then we run through all the elements with the each loop.
We take the first one, compare by "currency" whether it is not in the array, then add it (depending on which array was selected, add either only "currency" and "amount" to it, or an object). If there is already a similar one in the array, then we add it to the existing one.
Example:

var jsonObj = $.parseJSON('[{"id":1, "amount":123, "currency" : "CHF"},{"id":2, "amount":321, "currency" : "USD"},{"id":3, "amount":4324, "currency" : "UAH"},{"id":4, "amount":45645, "currency" : "USD"},{"id":5, "amount":8972, "currency" : "CHF"}]');
var data = {};

  $.each(jsonObj, function(index, value){
    if(!data.hasOwnProperty(value.currency)){
      data[value.currency] = value.amount;
    }else{
      data[value.currency] = data[value.currency] + parseInt(value.amount);
    }
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question