Answer the question
In order to leave comments, you need to log in
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'}]
123 CHF
321 USD
4324 UAH
45645 USD
8972 CHF
9095 CHF
45966 USD
4324 UAH
Answer the question
In order to leave comments, you need to log in
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}
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 questionAsk a Question
731 491 924 answers to any question