Here are two objects:
const obj1 = {a: null, b: "b"}
const obj2 = {a: "a", b: null}
How can I merge the two objects and get the following object?
{a: "a", b: "b"}
I can do this:
const merged = {...obj1, ...obj2}
But it returns this:
{ a: "a", b: null }
Is there a way to merge two objects while prefering not null (nor empty, undefined, etc.) values?
In the above example, two objects are merged into one using the Object. assign() method. The Object. assign() method returns an object by copying the values of all enumerable properties from one or more source objects.
To merge two objects in JavaScript, you can use the spread ... operator. The spread operator creates a new object with all the properties from the first and second object. If there's two properties with the same name, the property from the second object wins out.
function merge(obj1, obj2) {
answer = {}
for(key in obj1) {
if(answer[key] === undefined || answer[key] === null)
answer[key] = obj1[key];
}
for(key in obj2) {
if(answer[key] === undefined || answer[key] === null)
answer[key] = obj2[key];
}
return answer
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With