Necesito ayuda de expertos en nodos... La versión que debo usar es 0.10.x
Tengo una matriz como esta:
[ [ 'ABC', '5' ] , [ 'BCD', '1' ] ] y tengo nuevos valores para ingresar [ 'DDD', '3' ] y [ 'ABC', '4' ] y lo que me gustaría lograr es buscar si la primera columna existe en la matriz; en caso afirmativo, resuma la segunda columna, si no solo agrega valores a la matriz.
Como resultado, esperaría tener:
agregar [ 'DDD', '3' ] - DDD no existe en la matriz a la que se agregará
[ [ 'ABC', '5' ] , [ 'BCD', '1' ] , [ 'DDD', '3' ] ]
agregue [ 'ABC', '4' ] - ABC existe en la matriz, por lo que la segunda columna se resumirá para ABC
[ [ 'ABC', '9' ] , [ 'BCD', '1' ] , [ 'DDD', '3' ] ]
Por favor ayuda
El valor inicial de sus objetos:
var myObj = [{'ABC': '5'}, {'BCD': '1'}] Ahora, si DDD no existe, simplemente agréguelo:
var DDD = "3" var DDDExists = false; myObj.forEach(function(){ if(this.DDD.length > 0){ // If it exists, break the loop DDDExists = true; break; } }) // If DDD doesn't exists, add it if(DDDExists === false){ // Add DDD object to array myObj.push({'DDD': 3}); } Ahora, si existe ABC , suma ABC a todos los valores disponibles:
// Check if ABC exists var ABCExsits = false; myObj.forEach(function(){ if(this.ABC.length > 0){ // If ABC exits, break the loop ABCExists = true; break; } }) if(ABCExists === true){ // Sum all the values var totalSum = 0; myObj.forEach(function(){ // Since we don't know the name property of the obj, we need to do a for loop for(var prop in this){ totalSum = totalSum + this[prop]; } }) // Now add `totalSum` to ABC myObj.foreach(function(){ if(this.ABC.length > 0){ this.ABC = totalSum; break; } }) }