0

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

10
  • What's wrong with using in? Commented Mar 10, 2012 at 22:13
  • 1
    @amnotiam For example, imagine a key called toString. 'toString' in {} is true.` Commented Mar 10, 2012 at 22:14
  • @RobW: By uri contents, I would assume that specific keys are used for the different parts. Unless perhaps it's going to separate out the querystring parameters into keys. Commented Mar 10, 2012 at 22:17
  • 1
    @yoda The uri will never be parsed, because uri.segments.length == undefined (it is not an array). undefined == 0 is false. Commented Mar 10, 2012 at 22:21
  • 1
    @RobW Thank you, I failed to see that. Changed it to segments : [] and it worked :) Commented Mar 10, 2012 at 22:29

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

It says the key doesn't exist, but If I call it directly it displays the right result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.