假设我有以下对象:
const obj = {
'myApi': ['keyOne', 'keyTwo'],
'myApi.keyOne': ['three', 'four'],
'myApi.keyTwo': [...],
'myApi.keyOne.three': [...]
'myApi.keyOne.four': [...]
}
现在,基于以下字符串:
const str = "if(myApi.keyOne.three"
我想匹配正确的对象键,但是从从右到左。所以,在上面的例子中,我想得到 obj["myApi.keyOne.three"]
.
indexOf
或str.test
方法将不起作用,因为它们会捕获 myApi
和myApi.keyOne
还有。
请注意,它可以是任何字符串,即 str
这只是一个例子。例如:
while(myApi.keyOne.three) {} // should match obj["myApi.keyOne.three"]
if(myApi.keyOne) {} // should match obj["myApi.keyOne"]
等等
我该怎么做?
最佳答案
要获取 key ,请使用正则表达式来匹配 myApi
,后跟任意数量的重复组(句点后跟单词字符)。然后,您可以访问对象上适当的键:
const obj = {
'myApi': ['keyOne', 'keyTwo'],
'myApi.keyOne': ['three', 'four'],
'myApi.keyOne.three': ['foobar']
};
function getVal(str) {
const key = str.match(/myApi(?:\.\w+)*/)[0];
console.log(obj[key]);
return obj[key];
}
getVal("if(myApi.keyOne.three");
getVal("while(myApi.keyOne.three) {}");
getVal("if(myApi.keyOne) {}");
关于javascript - JS从右到左匹配字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52922510/