Search code examples
javascriptlodash

Get only object key values which have non blank using lodash


I have an array which has specific keys of an object obj

arr_keys = ['key1','key4','key5'];

And I also have an object with key value pair as below

obj = { 'key1' : '', 'key2' : 'val2', 'key3' : '', 'key4' : 'val4', 'key5' : '' };

Now I am looking for some function in lodash which could give me x object filtered from obj object as

 x = _.someFunc(obj,arr_keys)

// x = { 'key4' : 'val4'  }

We can see that I have only got key value pair of 'key4' : 'val4' and ommited keys 'key1' and 'key5' as they had blank values


Solution

  • You could chain pickBy and identity to get properties where value is not empty string or undefined and then use pick method to get only properties where key is in array.

    const arr = ['key1','key4','key5'];
    const obj = { 'key1' : '', 'key2' : 'val2', 'key3' : '', 'key4' : 'val4', 'key5' : '' };
    const result = _(obj).pickBy(_.identity).pick(arr).value()
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>