Reputation: 570
I have a JavaScript Object filled with key/value pairs and I would like to search one with a regex. 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!
Upvotes: 1
Views: 3823
Reputation: 386746
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);
Upvotes: 1
Reputation: 19133
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)
Upvotes: 2