Search code examples
javascriptlodash

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. But is it possible to replace that with a lodash function?

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));

Solution

  • I think _.assignWith is what you're looking for:

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