Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge properties of two JavaScript objects and prefer not null values?

Tags:

javascript

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?

like image 579
rap-2-h Avatar asked Jul 18 '18 14:07

rap-2-h


People also ask

How do you combine properties of two objects?

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.

How do I combine two JavaScript 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.


1 Answers

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
}
like image 198
Bruno Braga Avatar answered Sep 30 '22 04:09

Bruno Braga