6

I have an object where some fields have a value of null or undefined. Is there a nice quick way to change these values to an empty string '' using Javascript or Lodash?

Example input:

{
  a: '23',
  b: 'Red',
  c: null,
}

Example output:

{
  a: '23',
  b: 'Red',
  c: '',
}

NOTE: I do NOT want to remove these fields with values of null or undefined, I want to keep them in the object but change their values to the empty string ''

Thanks

2 Answers 2

3

You can use _.mapValues() to iterate the values and replace them, and _.isNil() to check if a value is null or undefined:

const obj = {
  a: '23',
  b: 'Red',
  c: null,
}

const result = _.mapValues(obj, v => _.isNil(v) ? '' : v)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

This is very nice thank you! Accepting this answer instead as it is shorter and easier to read
3

You can use a combination of Object.keys() and .forEach():

Object.keys(yourObject).forEach(function(key, index) {
  if (this[key] == null) this[key] = "";
}, yourObject);

The == comparison will check for both null and undefined. Passing yourObject as the second parameter to .forEach() will cause this to be bound to it inside the callback function.

edit — originally I wrote this as an => function, but that won't work because we need this to work in the traditional way.

6 Comments

@tnoel999888 without seeing your actual code it's going to be hard to help. You can edit it into your question.
ah fair enough, edited the post to include my actual code
@tnoel999888 oh oh sorry, my bad; it'll need an old-style function. I'll update the answer.
@tnoel999888 sorry I don't use => functions in my own code due to various particular constraints I'm under, so I'm not really used to thinking about how they work etc :)
Thanks working now! Accepted answer. Also would it be possible instead of having both arguments (key, index) i could just have one say field and then it becomes if (field == null) field = "";?
|

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.