skip to Main Content

I’m using lodash and have this code right now

data: _(responseData.data)
     .pick(['title', 'layout', 'slug', 'author', 'seo', 'css', 'js'])
     .mapKeys((value, key) => _.camelCase(key))
     .value()

Some of the values can be returned as null from the database. I would like to replace null values with an empty string -> ” but I’m not sure how to chain another function to above chain.

2

Answers


  1. You can use || Operator

    _((responseData && responseData.data) || {})
         .pick(['title', 'layout', 'slug', 'author', 'seo', 'css', 'js'])
         .mapKeys((value, key) => _.camelCase(key))
         .value()
    
    Login or Signup to reply.
  2. Use _.mapValues() to iterate the values, and check with _.isNull() if the value is null.

    Note: if you want to handle undefined values as well, replace _.isNull() with _.isNil().

    const responseData = {
      data: {
        'title': 'title',
        'layout': null,
        'slug': null,
        'author': 'author',
        'seo': 'seo',
        'css': 'css',
        'js': 'js'
      }
    }
    
    const data = _(responseData.data)
      .pick(['title', 'layout', 'slug', 'author', 'seo', 'css', 'js'])
      .mapKeys((value, key) => _.camelCase(key))
      .mapValues(value => _.isNull(value) ? '' : value)
      .value()
    
    console.log(data)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search