Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!