To aggregate the values you can use the following function:
function somarRegioes(vendas)
{
totais = {};
obs = Object.keys(vendas).map(function (key1)
{
var obs_vendas = vendas[key1];
Object.keys(obs_vendas).map(function (key2)
{
var regiao = obs_vendas[key2]['Regiao'];
// Se a região ainda não existir em totais.
if(totais[regiao] === undefined)
totais[regiao] = 0;
totais[regiao] += obs_vendas[key2]['Valor'];
});
});
return totais;
}
Or with that:
function somarRegioes(vendas)
{
totais = {};
for(var obs in vendas)
{
for(var venda in vendas[obs])
{
var regiao = vendas[obs][venda]['Regiao'];
// Se a região ainda não existir em totais.
if(totais[regiao] == undefined)
totais[regiao] = 0;
totais[regiao] += vendas[obs][venda]['Valor'];
}
}
return totais;
}
What turns out to be:
vendas = {obs1:{Venda1:{Regiao:"Norte", Valor: 200}, Venda2:{Regiao:"Sul", Valor:100}}, obs2:{Venda1:{Regiao:"Norte", Valor: 50}, Venda2:{Regiao:"Sul", Valor:20}}}
resultado = somarRegioes(vendas); // output = Object {Norte: 250, Sul: 120}
I find it a little complicated to do this without loops, because it will occur even indirectly, because the input is dynamic.
Are you up to using a library? Underscore greatly simplifies the solution.
– bfavaretto
Of course, what I want in the background is to find libraries that facilitate data manipulation in JS. But to ask that would be very open, so I thought I’d give an example!
– Carlos Cinelli
Well, I got in late and I already got a good response with underscore. But I thought the code would be more concise using this library... Compared to the pure JS code, I think I would end up using the second.
– bfavaretto