0

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}

5 Answers5

2

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)
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
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)
Steve
  • 878
  • 1
  • 5
  • 9
0
Object.fromEntries(Object.entries(obj1).map(e=>([e[0], obj1[e[0]]!=' '?obj1[e[0]]:obj2[e[0]]])))
AghaKhan
  • 64
  • 1
  • 12
0

You could filter the object and spread the first and filtered object.

const
    filter = o => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== ' ')),
    obj1 = { a: 1, b: 2, c: ' ', d: ' ', e: ' ' },
    obj2 = { a: ' ', b: ' ', c: 3, d: 5, e: ' ' },
    result = { ...obj1, ...filter(obj2) };

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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

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

/* in case your objects are not same length */
var longObj = obj1;
var shortObj = obj2;

if(Object.keys(obj1).length < Object.keys(obj2).length) {
  longObj = obj2;
  shortObj = obj1;
}

for(let k in shortObj) {
  longObj[k] = longObj[k] !== ' ' ? longObj[k] : shortObj[k]; 
}

console.log(longObj);
gökhan
  • 51
  • 3