假设我有以下对象:
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"]
等
我该怎么做?
答案 0 :(得分:1)
要获取密钥,请使用正则表达式匹配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) {}");
答案 1 :(得分:1)
搜索模式中的键条目:
var result = “”;
Object.keys(obj).forEach(function(key) {
if (str.indexOf(key) !== -1 && key.length > result.length) result = key;
});
console.log(obj[result]);
答案 2 :(得分:1)
使事情更具动态性(即使不能保证myApi
也是如此):
function findStuff(str, obj) {
const keys = Object.keys(obj);
keys.sort((a, b) => b.length - a.length);
// https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
const re = new RegExp(keys.map(key => key.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join('|'));
const match = str.match(re);
return match && match[0];
}
const obj = {
'myApi': ['keyOne', 'keyTwo'],
'myApi.keyOne': ['three', 'four'],
'myApi.keyTwo': [""],
'myApi.keyOne.three': ["THREE"],
'myApi.keyOne.four': [""]
}
console.log(findStuff('while(myApi.keyOne.three) {}', obj));
我们从对象中取出所有键,然后按降序对它们进行排序(因此最长的将首先匹配)。然后对它们进行正则表达式转义,并按正则表达式交替将它们粘在一起。
答案 3 :(得分:0)
您可以使用正则表达式,例如
myApi(\.\w+)*
详细信息:
myApi
-匹配"myApi"
字符串
(\.\w+)*
-匹配句号(.
)后面的那些字母数字字符串的 0个或更多重复
const obj = {
'myApi': ['keyOne', 'keyTwo'],
'myApi.keyOne': ['three', 'four'],
'myApi.keyTwo': ['someVlaue1'],
'myApi.keyOne.three': ['someVlaue2'],
'myApi.keyOne.four': ['someVlaue3']
}
var str1 = 'while(myApi.keyOne.three) {}';
var str2 = 'if(myApi.keyOne) {}';
var regex = /myApi(\.\w+)*/g;
var val1 = obj[ str1.match(regex)[0] ];
var val2 = obj[ str2.match(regex)[0] ];
console.log(val1);
console.log(val2);