如何迭代对象值并使用 lodash 将 undefined 替换为 null?

How to iterate an Objects values and replace undefined with null using lodash?

我知道如何使用本机 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));