简体   繁体   English

如何在JavaScript中使用正则表达式搜索键/值对?

[英]How to search a key/value pair with a regex in JavaScript?

I have a JavaScript Object filled with key/value pairs and I would like to search one with a regex. 我有一个用键/值对填充的JavaScript对象,我想用一个正则表达式搜索一个。 Here's an example: 这是一个例子:

var map = {
    'my/route/one': 'Title1',
    'my/route/two': 'Title2',
    '/': 'Home'
}

And I would like something like this: 我想要这样的事情:

var myValue = searchByKey(map, 'my/route/two');

I did this at first: 我最初是这样做的:

searchByKey: function (map, routePattern) {
    var foundTitle,
        route;
    for (route in map) {
        if (routePattern.match(route)) {
            foundTitle = map[route];
            break;
        }
    }
    return foundTitle;
}

It worked, great. 很好,很好。 Then, I wanted to have something more functional, so I thought of this: 然后,我想拥有更多功能,因此想到了这一点:

function searchByKey(map, routePattern) {
    var foundTitle;
    Object.keys(map).forEach(function(key) {
        if (routePattern.match(key)) {
            foundTitle = map[key];
        }
    });
    return foundTitle;
}

But it may match other keys like the last one '/' . 但是它可以匹配其他键,例如最后一个'/'

Do you have any idea on how achieve this in an elegant way? 您是否知道如何以一种优雅的方式实现这一目标?

Thanks! 谢谢!

You can simply do this! 您可以简单地做到这一点!

 function searchByKey(map, route) { return map[route] ? map[route] : 'not found' //return 'not found' when an invalid key is given } var map = { 'my/route/one': 'Title1', 'my/route/two': 'Title2', '/': 'Home' } var myValue = searchByKey(map, 'my/route/two') console.log(myValue) 

Why not use the key directly? 为什么不直接使用密钥?

 function searchByKey(object, key) { return object[key]; } var map = { 'my/route/one': 'Title1', 'my/route/two': 'Title2', '/': 'Home' } var myValue = searchByKey(map, 'my/route/two'); console.log(myValue); 

Another attempt with splitted keys 再次尝试使用分割键

 function searchByKey(object, key) { var items = key.split('/'); return Object.keys(object).filter(function(k) { return items.every("".match.bind(k)); }); } var map = { 'my/route/one': 'Title1', 'my/route/two': 'Title2', '/': 'Home' }, myKeys = searchByKey(map, 'my/route/two'); console.log(myKeys); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM