2

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));
2
  • Your code creates a whole new object on each iteration of .reduce(), copying all properties accumulated so far. Instead you could just set acc[key] as necessary and return acc. Commented Jul 7, 2021 at 22:55
  • 1
    Have you tried _.reduce()? Commented Jul 7, 2021 at 22:55

2 Answers 2

4

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

const nulledObject = _.assignWith({}, object, 
    (_, value) => typeof value == 'undefined' ? null : value);
Sign up to request clarification or add additional context in comments.

Comments

3

I found another solution after posting this question:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.