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
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
Share Improve this question edited May 10, 2019 at 15:44 Jordan Running 106k18 gold badges188 silver badges187 bronze badges asked May 10, 2019 at 13:18 tnoel999888tnoel999888 6543 gold badges14 silver badges29 bronze badges2 Answers
Reset to default 3You 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./ajax/libs/lodash.js/4.17.11/lodash.js"></script>
You can use a bination of Object.keys()
and .forEach()
:
Object.keys(yourObject).forEach(function(key, index) {
if (this[key] == null) this[key] = "";
}, yourObject);
The ==
parison 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.