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

127
Vistas
Check if property of object exists within second object

I want to check if a property in a first object exists within a second object and change it's value if it's different, dinamically. The first object properties may change because it's created dinamically too, and the second object's properties are always the same.

The logic I need to find it's the following, but instead of doing it manually (checking every property and value with a different if clause) is there any way of creating a function that does this dinamically? I am using vanilla javascript

function mapObject2(obj1) {
    if (sessionStorage.getItem("obj2") != null) {
        var obj2 = JSON.parse(sessionStorage.getItem("obj2"))
        if (obj1.Color != obj2.Color) {
            obj1.Color = obj2.Color
        }
    }
}

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

0

You can use Object.assign() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

function mapObject2(obj1) {
    if (sessionStorage.getItem("obj2") != null) {
        var obj2 = JSON.parse(sessionStorage.getItem("obj2"))
        Object.assign(obj1, obj2)
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use Object.assing as @krasi said but the correct syntax is this

function mapObject2(obj1) {
    if (sessionStorage.getItem("obj2") != null) {
        var obj2 = JSON.parse(sessionStorage.getItem("obj2"))
        Object.assign(obj1, obj2)
    }
}

if you want to return a new object that is the merge of obj1 and obj2 you can do this

function mapObject2(obj1) {
    if (sessionStorage.getItem("obj2") != null) {
        const obj2 = JSON.parse(sessionStorage.getItem("obj2"))
        return {...obj1, ...obj2} 
        //or
        return Object.assign({}, obj1, obj2)
    }
   return obj1
}
function mapObject2(obj1) {
    if (sessionStorage.getItem("obj2") != null) {
        const obj2 = JSON.parse(sessionStorage.getItem("obj2"))
        Object.keys(obj1).forEach(k => {
          obj1[k] = obj2[k] || obj1[k]
        })
    }
}

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