Reputation: 10981
I'm building a object in Javascript to parse the uri contents and attach their key / value pairs to it. However, I'm stuck on how to find out if a key exists. Here's the code :
var uri = {
segments : {},
parse : function() {
var segments = {};
var parts;
var s;
parts = location.href.split('/');
parts = parts[3].split('?');
parts = parts[1].split('&');
for (var i = 0; i < parts.length; i++) {
s = parts[i].split('=');
segments[s[0]] = s[1];
}
uri.segments = segments;
return segments;
},
segment : function(key) {
if (uri.segments.length == 0)
{
uri.parse();
}
/* before was 'key in uri-segments' */
if (Object.prototype.hasOwnProperty.call(uri.segments, key))
{
return uri.segments[key];
}
else
{
return false
}
},
};
edit : full code
Upvotes: 0
Views: 7852
Reputation: 348992
Use the hasOwnProperty
method to check whether a key exists or not:
// hasOwnProperty from the objects prototype, to avoid conflicts
Object.prototype.hasOwnProperty.call(uri.segments, key);
// ^ object ^ key
Upvotes: 7