我有一个如下所示的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' } } }发布于 2020-05-02 21:18:56
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]数组。
发布于 2020-05-02 21:19:09
正如您尝试使用.match()的注释中所提到的,您只需将config.conf转换为数组,然后使用Object.keys()遍历它,以下是您想要的代码片段:
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);
https://stackoverflow.com/questions/61559727
复制相似问题