Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick keys from object which contains specific string as substring in Javascript

I am having an array like:

var arr = ["hello","world"] 
// This array can contain any number of strings

Object like this:

var obj_arr = {
  "abc-hello-1": 20,
  "def-world-2": 30,
  "lmn-lo-3": 4
}

I want to have an object which contains only those keys, which contains above array values as substrings. For eg:

Result will look like :

var result = {
  "abc-hello-1": 20,
  "def-world-2": 30,
}

I want to do something like this (using lodash) :

var to_be_ensembled = _.pickBy(timestampObj, function(value, key) {
  return _.includes(key, "hello");
  // here instead of "hello" array should be there
});
like image 973
Ashag Avatar asked Aug 18 '26 22:08

Ashag


1 Answers

With lodash you can use _.some() to iterate the strings arrays, and to check if the key includes any of the strings.

const arr = ["hello", "world"]

const timestampObj = {
  "abc-hello-1": 20,
  "def-world-2": 30,
  "lmn-lo-3": 4
}

const to_be_ensembled = _.pickBy(timestampObj, (value, key) =>
  _.some(arr, str => _.includes(key, str))
);

console.log(to_be_ensembled);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
like image 50
Ori Drori Avatar answered Aug 20 '26 13: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!