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}
Solution 1:
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)