Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get keys using Lodash with only partial key string

Is it possible to use LoDash _.filter to return values if you only know a key contains a certain string? So let's say you have the following data:

Mydata{
"banana" : "1"
}

And I want to return the values that contain "ana"? Everything I found on LoDash is mostly about searching the element values but not the keys.


1 Answers

If you want to get an array of the values, which keys conform to a criterion, Lodash's _.filter() works with objects as well. The 2nd param passed to the callback is the key.

var data = {
  "banana": 1,
  'lorem': 2,
  '123ana': 3
}

var result = _.filter(data, function(v, k) {
  return _.includes(k, 'ana');
});

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

If you want an object, which properties conform to a certain criterion, you can use _.pickBy() in a similar way.

var data = {
  "banana": 1,
  'lorem': 2,
  '123ana': 3
}

var result = _.pickBy(data, function(v, k) {
  return _.includes(k, 'ana');
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
like image 150
Ori Drori Avatar answered Aug 20 '26 12:08

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!