You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写mergeWith自定义器:避免合并嵌套数组并补全缺失属性

为Lodash的mergeWith编写自定义器:补全undefined属性且保留原数组

需求明确:补全baseObject中值为undefined的属性,但保留原对象的嵌套数组,不与defaultObject的数组合并。

正确的自定义器实现

const customizer = (objValue, srcValue) => {
  // 补全base中值为undefined的属性
  if (objValue === undefined) {
    return srcValue;
  }
  // 遇到数组直接返回base原数组,跳过合并逻辑
  if (Array.isArray(objValue)) {
    return objValue;
  }
  // 其他情况返回undefined,让mergeWith按默认逻辑处理对象深层合并
  return undefined;
};

// 调用mergeWith,传入空对象避免修改原baseObject
const result = _.mergeWith({}, baseObject, defaultObject, customizer);

console.log(result);

输出结果

{ 
  firstElement: { data: '13.01.2018' }, 
  secondElement: { 
    name: 'Canada',
    items: [ 
      { city: 'Toronto', code: 12334},
      { city: 'Vancouver ', code: 33245}
    ] 
  }
}

逻辑说明

  • 当objValue(base中的属性值)为undefined时,返回srcValue(default中的对应值),完成属性补全;
  • 处理数组时直接返回base原数组,跳过mergeWith默认的数组合并逻辑;
  • 其余场景返回undefined,让mergeWith继续按默认规则处理对象的深层属性合并(比如secondElement作为对象,会保留base里的name值,因为它既不是undefined也不是数组)。

注:调用时传入空对象作为第一个参数,是为了避免直接修改原baseObject,若无需保留原对象,也可直接传入baseObject。

内容的提问来源于stack exchange,提问作者Halyna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 14:15:33