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

140
Vistas
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 Respuestas
Responde la pregunta

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 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