最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

lodash - Javascript how to set nullundefined values in an Object to an empty string - Stack Overflow

programmeradmin4浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 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./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.

发布评论

评论列表(0)

  1. 暂无评论