简体   繁体   中英

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

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>

Using only javascript you can acheive this using array forEach & Object.Keys function

 var arr = ["hello", "world"] var obj_arr = { "abc-hello-1": 20, "def-world-2": 30, "lmn-lo-3": 4 } var resultObj = {}; // get all the keys from the object var getAllKeys = Object.keys(obj_arr); arr.forEach(function(item) { // looping through first object getAllKeys.forEach(function(keyName) { // using index of to check if the object key name have a matched string if (keyName.indexOf(item) !== -1) { resultObj[keyName] = obj_arr[keyName]; } }) }) console.log(resultObj)

Try this code

var result = _.map(arr, function(s){
  return _.pickBy(timestampObj, function(v, k){
    return new RegExp(s,"gi").test(k)
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM