JSFiddle - React, Tailwind, and code Playground

by mgibsonbr

JavaScript

vendas = {
        obs1: {
            Venda1: {
                Regiao: "Norte",
                Valor: 200
            },
            Venda2: {
                Regiao: "Sul",
                Valor:100
            }
        }, 
        
        obs2:{
            Venda1: {
                Regiao: "Norte",
                Valor: 50
            }, 
            Venda2: {
                Regiao: "Sul",
                Valor: 20
            }
        }
    };
    
    var totais = _
        .chain(vendas)
        // Primeiro, "achatar" as vendas
        .map(function(v) { 
            return _
            .chain(v)
            .map(function(v2) {
                return v2;
            })
            .value(); 
        })
        .flatten()
         // Segundo: agrupar as vendas por região
        .groupBy('Regiao')
        // Terceiro: somar os agrupamentos e criar o objeto com os totais
        .map(function(g, key) {
            return {
                type: key, 
                val: _(g).reduce(function(m, x) {
                    return m + x.Valor;
                }, 0)
            };
        })
        .value();
    
    console.log(totais);