Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

215
Vistas
how to merge 2 object arrays based on keys in JavaScript and retain values of both the arrays when matched

I am trying to merge 2 object arrays(can be more as well) of same order and fields based on 2 keys. and if the keys matched then maintain the values of array1 and array2. For example:

var array1 = [
    { "id": 11, "smid":21, "name":'test1a', "value":0.5 },
    { "id": 12, "smid":22, "name":'test1b', "value":0.6 },
    { "id": 13, "smid":null, "name":'test1b', "value":0.7 }
]
var array2 = [
    { "id": 11, "smid":21, "name":'test2a', "value":1.5 },
    { "id": 22, "smid":32, "name":'test2b', "value":1.6 }
    { "id": 13, "smid":null, "name":'test2c', "value":1.7 },
]

The result has to be

var resultedArray = [
    { "id": 11, "smid":21, "name":'test1a', "value":0.5, "newValue":[0.5,1.5] },
    { "id": 12, "smid":22, "name":'test1b', "value":0.6, "newValue":[0.6, null] },
    { "id": 13, "smid":null, "name":'test1b', "value":0.7, "newValue":[0.7,1.7] }
]

I am able to achieve the above result with the following code.

var idFound = false;
for(var ar1Inx = 0; ar1Inx < array1.length;  ar1Inx++){
    idFound = false;
    for(var ar2Inx = 0; ar2Inx < array2.length;  ar2Inx++){
        if(array1[ar1Inx].id == array2[ar2Inx].id && array1[ar1Inx].smid == array2[ar2Inx].smid){
            idFound = true;
            var newArray = [];
            newArray.push(array1[ar1Inx].value);
            newArray.push(array2[ar2Inx].value);
            array1[ar1Inx].["newValue"] = newArray;
        }
    }
    if(!idFound){
        var newArray = [];
        newArray.push(array1[ar1Inx].value);
        newArray.push(null);
        array1[ar1Inx].["newValue"] = newArray;
    }
}

But, I want to know, is there a way that I can achieve the expected result in a simple way instead of iterating through each of the arrays which is supported in Internet Explorer 11 with 2 or more arrays. Please advice. Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You could take an object for reference and an array for collecting.

// function expects arrays as arguments
function leftJoin() {
    function getKey(object) {
        return ['id', 'smid']
            .map(function (k) { return object[k]; })
            .join('|');
    }

    function add(array, index) {
        for (var i = 0; i < array.length; i++) {
            var object = array[i],
                key = getKey(object);

            if (!reference[key]) continue;
            reference[key].value[index] = object.value;
        }
    }
    
    var reference = {},
        result = [];
    
    for (var i = 0; i < arguments[0].length; i++) {
        var object = arguments[0][i],
            key = getKey(object);

        reference[key] = { id: object.id, smid: object.smid, name: object.name, value: [object.value] };
        for (var j = 1; j < arguments.length; j++) reference[key].value[j] = null;
        result.push(reference[key]);
    }

    for (var i = 1; i < arguments.length; i++) add(arguments[i], i);
    
    return result;
}

var array1 = [{ id: 11, smid: 21, name: 'test1a', value: 0.5 }, { id: 12, smid: 22, name: 'test1b', value: 0.6 }, { id: 13, smid: null, name: 'test1b', value: 0.7 }],
    array2 = [{ id: 11, smid: 21, name: 'test2a', value: 1.5 }, { id: 22, smid: 32, name: 'test2b', value: 1.6 }, { id: 13, smid: null, name: 'test2c', value: 1.7 }];

console.log(leftJoin(array1, array2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda