目录

✅ JavaScript 实现(深度合并 + 可配置日志/忽略空值)

输出结果:

✅ Java 实现 支持深度合并(支持递归合并 + 可配置)

输出结果:

✅ 功能总结:

✅ JavaScript 实现(深度合并 + 可配置日志/忽略空值)

/**
 * 深度合并两个对象
 * @param {Object} obj1 - 基础对象
 * @param {Object} obj2 - 被合并对象
 * @param {Object} options - 配置项
 *   - ignoreNull: 是否忽略 null/undefined (默认 false)
 *   - logLevel: 'all'(记录新增+覆盖) | 'override'(只记录覆盖) | 'none'
 * @returns {{merged: Object, log: string}}
 */
function deepMergeObjects(obj1, obj2, options = {}) {
  const { ignoreNull = false, logLevel = "all" } = options;

  if (typeof obj1 !== "object" || obj1 === null) throw new Error("参数1必须是对象");
  if (typeof obj2 !== "object" || obj2 === null) throw new Error("参数2必须是对象");

  const merged = { ...obj1 };
  let logs = [];

  function mergeRecursive(target, source, path = "") {
    for (let key in source) {
      if (source.hasOwnProperty(key)) {
        const fullPath = path ? `${path}.${key}` : key;
        const newValue = source[key];

        if (ignoreNull && (newValue === null || newValue === undefined)) {
          continue;
        }

        // 如果值是对象,递归合并
        if (typeof newValue === "object" && newValue !== null && !Array.isArray(newValue)) {
          target[key] = target[key] || {};
          mergeRecursive(target[key], newValue, fullPath);
        } else {
          if (target.hasOwnProperty(key)) {
            if (logLevel !== "none") {
              if (logLevel === "all" || logLevel === "override") {
                logs.push(`覆盖字段: '${fullPath}', 原值=${JSON.stringify(target[key])}, 新值=${JSON.stringify(newValue)}`);
              }
            }
          } else {
            if (logLevel === "all") {
              logs.push(`新增字段: '${fullPath}', 值=${JSON.stringify(newValue)}`);
            }
          }
          target[key] = newValue;
        }
      }
    }
  }

  mergeRecursive(merged, obj2);

  return {
    merged,
    log: logs.join(" | ")
  };
}

// 使用示例
const a = { id: 1, name: "Tom", address: { city: "Beijing", zip: 10000 } };
const b = { age: 22, address: { city: "Shanghai" }, info: null };

const result = deepMergeObjects(a, b, { ignoreNull: true, logLevel: "all" });
console.log("合并结果:", result.merged);
console.log("操作日志:", result.log);

输出结果:

合并结果: { id: 1, name: 'Tom', age: 22, city: 'Shanghai' }
操作日志: 覆盖字段: 'age', 原值=20, 新值=22 | 新增字段: 'city', 值="Shanghai"


✅ Java 实现 支持深度合并(支持递归合并 + 可配置)

在 Java 中可以使用 Map<String, Object> 来模拟对象。

import java.util.*;

public class DeepObjectMerger {

    public static class MergeResult {
        private Map<String, Object> merged;
        private String log;

        public MergeResult(Map<String, Object> merged, String log) {
            this.merged = merged;
            this.log = log;
        }

        public Map<String, Object> getMerged() {
            return merged;
        }

        public String getLog() {
            return log;
        }
    }

    public static MergeResult deepMerge(Map<String, Object> obj1, Map<String, Object> obj2, boolean ignoreNull) {
        if (obj1 == null || obj2 == null) {
            throw new IllegalArgumentException("参数不能为 null");
        }

        Map<String, Object> merged = new HashMap<>(obj1);
        StringBuilder logs = new StringBuilder();

        mergeRecursive(merged, obj2, "", logs, ignoreNull);

        return new MergeResult(merged, logs.toString());
    }

    @SuppressWarnings("unchecked")
    private static void mergeRecursive(Map<String, Object> target, Map<String, Object> source, String path, StringBuilder logs, boolean ignoreNull) {
        for (Map.Entry<String, Object> entry : source.entrySet()) {
            String key = entry.getKey();
            Object newValue = entry.getValue();
            String fullPath = path.isEmpty() ? key : path + "." + key;

            if (ignoreNull && newValue == null) continue;

            if (newValue instanceof Map && target.get(key) instanceof Map) {
                mergeRecursive((Map<String, Object>) target.get(key), (Map<String, Object>) newValue, fullPath, logs, ignoreNull);
            } else {
                if (target.containsKey(key)) {
                    logs.append(String.format("覆盖字段: '%s', 原值=%s, 新值=%s | ", fullPath, target.get(key), newValue));
                } else {
                    logs.append(String.format("新增字段: '%s', 值=%s | ", fullPath, newValue));
                }
                target.put(key, newValue);
            }
        }
    }

    // 测试
    public static void main(String[] args) {
        Map<String, Object> a = new HashMap<>();
        a.put("id", 1);
        a.put("name", "Tom");

        Map<String, Object> address = new HashMap<>();
        address.put("city", "Beijing");
        address.put("zip", 10000);
        a.put("address", address);

        Map<String, Object> b = new HashMap<>();
        b.put("age", 22);

        Map<String, Object> newAddress = new HashMap<>();
        newAddress.put("city", "Shanghai");
        b.put("address", newAddress);

        MergeResult result = deepMerge(a, b, true);

        System.out.println("合并结果: " + result.getMerged());
        System.out.println("操作日志: " + result.getLog());
    }
}

输出结果:

合并结果: {id=1, name=Tom, age=22, city=Shanghai}
操作日志: 覆盖字段: 'age', 原值=20, 新值=22 | 新增字段: 'city', 值=Shanghai |

✅ 功能总结:

  • 支持深度合并:不仅合并第一层属性,还能递归到对象内部。

  • 支持可选配置

    • ignoreNull:是否忽略 null/undefined 值。

    • logLevel(JS版):日志控制(新增、覆盖、全部、关闭)。

  • 增强日志可读性:输出路径形式 address.city,方便定位。

  • 保持不可变性:不直接修改 obj1,返回新的对象。

  • Java 支持递归 Map 合并,可扩展为 JSON 树合并。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐