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
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 Respostas
Responde à pergunta

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 Relatório

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