【问题标题】:Getting hash values from regex loop?从正则表达式循环中获取哈希值?
【发布时间】:2020-05-02 12:56:33
【问题描述】:

我有一个如下所示的 JSON 对象,我想在其中循环匹配 u[0-9][0-9][0-9] 的条目。 This answer 接近于我要查找的内容,但我想要的是获取哈希值。

如果我这样做:

const config = toml('config.toml')

config.match(/u[0-9][0-9][0-9]/g).forEach((element) => {
  console.log(element)
});

然后我得到以下错误:

TypeError: config.match is not a function

问题

我将如何遍历这个 JSON 对象并从匹配 u[0-9][0-9][0-9] 的键中获取值?

{ conf:
   { url: 'https://example.com',
     u150: 'Log entry severity',
     u160: 'Log entry',
     d105: 'Check interval',
     d107: 'Incident cool down time',
     d120: 'Incident impact',
     d130: 'Incident urgency',
     d180: 'Implementeret i Produktion' },
  projects:
   { d1:
      { page_id: 104637,
        page_title: 'Moni' },
     k1:
      { page_id: 99999,
        page_title: 'Moni' } } }

【问题讨论】:

  • 我对你在这里想要达到的目标感到很困惑。是否要获取键匹配conf.u[0-9]{3} 的值?
  • 嗯,match 是一个字符串方法。您可能对Object.entries() 方法感兴趣

标签: javascript node.js ecmascript-6


【解决方案1】:

const config = { conf:
   { url: 'https://example.com',
     u150: 'Log entry severity',
     u160: 'Log entry',
     d105: 'Check interval',
     d107: 'Incident cool down time',
     d120: 'Incident impact',
     d130: 'Incident urgency',
   }
} // shortened your object

const matches = [];

for (let [key, value] of Object.entries(config.conf))
  {
    if(key.match(/u[0-9][0-9][0-9]/g))
      matches.push({ key, value })
  }
  
console.log(matches)  

我想出了这个主意。基本上我将对象拆分为[key, value]的数组。

【讨论】:

    【解决方案2】:

    正如评论中提到的,您尝试使用.match(),您可以将您的config.conf 转换为数组,然后使用Object.keys() 对其进行迭代,这是您想要的sn-p:

    let config = { conf:
       { url: 'https://example.com',
         u150: 'Log entry severity',
         u160: 'Log entry',
         d105: 'Check interval',
         d107: 'Incident cool down time',
         d120: 'Incident impact',
         d130: 'Incident urgency',
         d180: 'Implementeret i Produktion' },
      projects:
       { d1:
          { page_id: 104637,
            page_title: 'Moni' },
         k1:
          { page_id: 99999,
            page_title: 'Moni' } } }
    
    const conf = {}
    const matched = Object.keys(config.conf).filter(el => {
      return el.match(/u[0-9]{3}/g);
    }).forEach(el => conf[el] = config.conf[el]);
    
    console.log(conf);

    【讨论】:

      猜你喜欢
      • 2018-01-12
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 2022-06-14
      相关资源
      最近更新 更多