如何使用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
相关产品推荐
相关产品推荐

