从对象中选择键,其中包含特定字符串作为Javascript中的子字符串

时间:2017-08-03 04:11:26

标签: javascript json object lodash

我有一个像:

这样的数组
    var arr = ["hello","world"] 
// This array can contain any number of strings

像这样的对象:

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

我想要一个只包含那些键的对象,它包含上面的数组值作为子串。 例如:

结果如下:

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

我想做这样的事情(使用lodash):

var to_be_ensembled = _.pickBy(timestampObj, function(value, key) {
                return _.includes(key, "hello"); 
// here instead of "hello" array should be there
            });

3 个答案:

答案 0 :(得分:3)

只使用javascript即可使用数组forEach& Object.Keys函数



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)




答案 1 :(得分:2)

您可以使用_.some()迭代字符串数组,并检查该键是否包含任何字符串。



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

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

var to_be_ensembled = _.pickBy(timestampObj, function(value, key) {
  return _.some(arr, function(str) { // iterate the arr
    return _.includes(key, str); // if one of the strings is included in the key return true
  });
});

console.log(to_be_ensembled);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:2)

试试此代码

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