如何使用lodash迭代Object值并将undefined替换为null



我知道如何使用本机Object.entries和reducer函数来实现这一点。但是有可能用lodash函数来代替它吗?

const object = {
foo: 'bar',
baz: undefined,
}
const nulledObject = Object.entries(object).reduce(
(acc, [key, value]) => ({
...acc,
[key]: typeof value === 'undefined' ? null : value,
}),
{}
);
// {
//   foo: 'bar',
//   baz: null,
// }

我的愿望是:

_cloneWith(object, (value) => (typeof value === 'undefined' ? null : value));

我认为_.assignWith就是您想要的:

const nulledObject = _.assignWith({}, object, 
(_, value) => typeof value == 'undefined' ? null : value);

在发布这个问题后,我找到了另一个解决方案:

const nulledObject = _.mapValues(object, 
(value) => (value === undefined ? null : value));

最新更新