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

179
Views
Extracting a common Object from two Javascript objects with same keys

I have two Javascript objects with the same keys but the keys with some value in obj1 are empty in obj2 and vice versa. There can also be keys that are empty in both objects.

obj1 = {
 a: 1,
 b: 2,
 c: ' ',
 d: ' ',
 e: ' '
}

obj2 = {
 a: ' ',
 b: ' ',
 c: 3,
 d: 5,
 e: ' '
}

I want a combined object which contains the keys with values from both objects, and in case both the keys are empty it simply places it as empty

Expected result:

result = {
 a: 1,
 b: 2,
 c: 3,
 d: 5,
 e: ' '
}

I have tried using the spread operator but the second object always takes precedence over the first :> {...obj1, ...obj2}

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You could take advantage of the Object.keys method and the reduce one to create the result object

let obj1 = {
  a: 1,
  b: 2,
  c: ' ',
  d: ' ',
  e: ' '
}

let obj2 = {
  a: ' ',
  b: ' ',
  c: 3,
  d: 5,
  e: ' '
}
let result = Object.keys(obj1).reduce((acc, curr) => {
  val = obj1[curr] != " " ? obj1[curr] : obj2[curr];
  return { ...acc,
    ...{
      [curr]: val
    }
  }
}, {})

console.log(result)

about 4 years ago · Juan Pablo Isaza Report

0

You would have to build a common combined object and then loop through each of the other objects and add in the value if not empty

obj1 = {
    a: 1,
    b: 2,
    c: ' ',
    d: ' ',
    e: ' '
}

obj2 = {
    a: ' ',
    b: ' ',
    c: 3,
    d: 5,
    e: ' '
}

// Combine the two to get all keys into the combined object
var combined = { ...obj1, ...obj2 };

// Set each value in the combined object to a single spaced string
for (let key in combined) {
    combined[key] = ' ';
}

// Loop through each item in obj1 and add to combined if a single spaced string
for (let key in obj1) {
    if (obj1[key] !== ' ') combined[key] = obj1[key];
}

// Loop through each item in obj2 and add to combined if a single spaced string
for (let key in obj2) {
    if (obj2[key] !== ' ') combined[key] = obj2[key];
}

console.log(combined)

about 4 years ago · Juan Pablo Isaza Report

0

Object.fromEntries(Object.entries(obj1).map(e=>([e[0], obj1[e[0]]!=' '?obj1[e[0]]:obj2[e[0]]])))
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!