Search code examples
javascriptjsonobjectlodash

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
});

Solution

  • 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>