Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda