Search code examples
javascriptmergejavascript-objects

How to merge objects in JS only when they are defined?


I am learning JS and currently I need to 4 objects to merge with each other, but I have to make sure that in the result I will not have "undefined" inside the result object.

Currently, I implemented it like this:

  let result = {};
  result = Object.assign(result, first);
  if (second) result = Object.assign(result, second);
  if (third) result = Object.assign(result, third);
  if (fourth) result = Object.assign(result, fourth);
  return result;

But, I believe there must be a cleaner solution for this task. Are there any?


Solution

  • Object.assign ignores undefined argument values. You can simplify to

    return Object.assign({}, first, second, third, fourth);