代码之家  ›  专栏  ›  技术社区  ›  dvelopp

如何仅在JS中定义对象时合并它们?

  •  0
  • dvelopp  · 技术社区  · 7 年前

    我正在学习JS,目前我需要4个对象相互合并,但我必须确保在结果中我不会在result对象中有“undefined”。

    目前,我是这样实现的:

      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;
    

    但是,我相信这项任务必须有一个更干净的解决方案。 有吗?

    1 回复  |  直到 7 年前
        1
  •  4
  •   Bergi    7 年前

    Object.assign 忽略 undefined 参数值。你可以简化为

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