【问题标题】:Pick keys from object which contains specific string as substring in Javascript从包含特定字符串的对象中选择键作为Javascript中的子字符串
【发布时间】:2017-08-03 04:11:25
【问题描述】:

我有一个类似的数组:

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

【问题讨论】:

    标签: javascript json object lodash


    【解决方案1】:

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

    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>

    【讨论】:

      【解决方案2】:

      仅使用 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)

      【讨论】:

        【解决方案3】:

        试试这个代码

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-24
          • 2020-08-26
          • 2021-12-13
          • 1970-01-01
          • 2016-07-08
          • 2018-05-25
          • 2021-10-23
          相关资源
          最近更新 更多