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

136
Visualizações
How to combine two given nested JSON and return only the common values in another JSON in javascript?

For example I wanted to compare below 2 JSON and get the return value with common JSON key value pair.

JSON1 = [{
  "info" : {
    "name": "xyz"
  },
  "add" : "london",
  "no" : 1234,
  "gender" : "male"
}]

Another JSON is :

JSON2 = [{
  "info" : {
    "name": "abc"
  },
  "add" : "london",
  "no" : 2456
}]

Need return value as JSON like below with common values but difference should be empty.

json3 = [{
  "info" : {
    "name": ""
  },
  add : "london",
  no : "",
  gender : male
}]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could create a combineObjects() function that combines input objects recursively.

We'll enumerate the input objects keys, then return an empty value for each property if the values are not the same for the two inputs.

If the values are the same or are missing in either object, we'll return the value of the obj1 or obj2 property.

const json1 = [{ "info" : { "name": "xyz" }, "add" : "london", "no" : 1234, "gender" : "male" }];
const json2 = [{ "info" : { "name": "abc"}, "add" : "london", "no" : 2456 }];

function combineObjects(obj1, obj2) {
    const result = {};
    // Get all keys...
    let keys = [...new Set([...Object.keys(obj1), ...Object.keys(obj2)])];
    for(let k of keys) {
        if (obj1[k] && obj2[k] && typeof(obj1[k]) === 'object') {
            result[k] = combineObjects(obj1[k], obj2[k]);
        } else if (obj1[k] === obj2[k]) {
            result[k] = obj1[k];
        } else { 
            result[k] = (obj1[k] && obj2[k]) ? '' : obj1[k] || obj2[k];
        }
    }
    return result;
}

const result = combineObjects(json1, json2);
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js" integrity="sha512-Nw0Abk+Ywwk5FzYTxtB70/xJRiCI0S2ORbXI3VBlFpKJ44LM6cW2WxIIolyKEOxOuMI90GIfXdlZRJepu7cczA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

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