You need to enable JavaScript to run this app. 如何使用lodash遍历对象属性值并将undefined替换为null
优惠活动
大模型
产品
解决方案
定价
更多

如何使用lodash遍历对象属性值并将undefined替换为null

可以使用 Lodash 相关函数实现,对应两种不同场景的方案如下:

  • 若仅需处理单层对象,可直接使用_.mapValues,代码更简洁:
const _ = require('lodash');
const object = {
  foo: 'bar',
  baz: undefined,
};

const nulledObject = _.mapValues(object, value => typeof value === 'undefined' ? null : value);
  • 若需要处理嵌套层级的对象,使用你期望的_.cloneDeepWith即可实现递归转换:
const nulledObject = _.cloneDeepWith(object, value => {
  if (typeof value === 'undefined') return null;
});

_.cloneDeepWith 会自动递归遍历对象的所有层级,遇到undefined值时返回你指定的null,其余值走 Lodash 默认的深克隆逻辑,完全匹配你预期的调用形式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 14:03:02