Add elements of an array and leave one

-1

I have the following arrangement

var cargos = [{
        "TipoProducto": "Cargo",
        "Referencia": "IM",
        "Precio": 73710
    }, {
        "TipoProducto": "Cargo",
        "Referencia": "IM",
        "Precio": 32856

    }, {
        "TipoProducto": "Cargo",
        "Referencia": "IS",
        "Precio": 220970
    }, {
        "TipoProducto": "Cargo",
        "Referencia": "IS",
        "Precio": 98568
    }];

What I need to do is add the ones that are IM and add the ones that are IS, and I should have an arrangement

var cargos = [{
            "TipoProducto": "Cargo",
            "Referencia": "IM",
            "Precio": 106566
        },  {
            "TipoProducto": "Cargo",
            "Referencia": "IS",
            "Precio": 319538
    }];

Any ideas on how to do it in js

    
asked by Eduard 18.12.2017 в 16:08
source

1 answer

5

use the filter and map functions of javascript , it would be:

var im = cargos.filter(function(datos){
             return datos.Referencia == "IM"
         })
//en la variable im tendrás todos los IM , por si los necesitas luego
// ahora sumar los precios
var preciosIm=0;
    im.map(function(elemento){
       preciosIm += elemento.Precio  
     })

//para los IS seria de igual manera pero cambiando las búsquedas y las variables

   var iS = cargos.filter(function(datos){
             return datos.Referencia == "IS"
         })
//en la variable iS tendrás todos los IS , por si los necesitas luego
// ahora sumar los precios

var preciosIs=0;
    iS.map(function(elemento){
       preciosIs += elemento.Precio  
     })

You will have the variable im with all the data that is IM, the iS with all the IS, and you will have preciosIm and PricesIs with the sum of the prices of each one.

If you need to take everything to a single arrangement you would say:

//redefines el arreglo cargos
cargos = [{
        "TipoProducto": "Cargo",
        "Referencia": "IM",
        "Precio": preciosIm
    },  {
        "TipoProducto": "Cargo",
        "Referencia": "IS",
        "Precio": preciosIs
}];
    
answered by 18.12.2017 / 16:20
source