[英]How to iterate an Objects values and replace undefined with null using lodash?
I know how to do this using native Object.entries and a reducer function.我知道如何使用本机 Object.entries 和 reducer 函数来做到这一点。 But is it possible to replace that with a lodash function?
但是有可能用 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,
// }
My desire would be something like:我的愿望是这样的:
_cloneWith(object, (value) => (typeof value === 'undefined' ? null : value));
I think _.assignWith
is what you're looking for:我认为
_.assignWith
是你要找的:
const nulledObject = _.assignWith({}, object,
(_, value) => typeof value == 'undefined' ? null : value);
I found another solution after posting this question:发布此问题后,我找到了另一个解决方案:
const nulledObject = _.mapValues(object,
(value) => (value === undefined ? null : value));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.