0

This image will help explain my issue.

console log

This is the result of the console logs in the code below. The first console log prints out a key value pair array as epxected. The second console log prints out the values as expected, but then also a whole bunch of functions. This appears to be actually inside the value of the variable and is unusable as is.

I want to loop through the key value array without this noise. I've never come across this before. Unfortunately, I'm unsure what to try to fix this issue, very sorry about that.

Here is the code, function lightly altered from a stack overflow answer that is linked in the comment.

// http://stackoverflow.com/a/4656873/3774582
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        if (hash[1]) {
            vars[hash[0]] = hash[1];
        }
    }
    return vars;
}

var url_parameters = getUrlVars();
console.log(url_parameters);
for (var key in url_parameters) {
    var current_value = url_parameters[key];
    console.log(current_value);
}
8
  • 3
    var vars = [] should be var vars = {} - you're creating an object, not an array Commented Feb 29, 2016 at 20:30
  • if url_parameters.hasOwnProperty(key) {console.log(current_value);} Commented Feb 29, 2016 at 20:32
  • @Pamblam That gives expected behavior! I'll leave a comment in the answer I based my code on. Post it as the answer here and I'll accept it. Commented Feb 29, 2016 at 20:35
  • Please try using if (url_parameters.hasOwnProperty(key)) Commented Feb 29, 2016 at 20:37
  • @Vatsal That works as well, but changing [] to {} is more lean. Commented Feb 29, 2016 at 20:39

2 Answers 2

1

var vars = [] should be var vars = {}

objects are basically associative arrays with functions in javascript.

Sign up to request clarification or add additional context in comments.

Comments

1

You have some library that's adding properties to the object's prototype. These are still iterable, but don't show up when console.log()ing the object because that only shows the object's own properties.

You should only run the log in your loop if url_parameters.hasOwnProperty(key).

Also, as Pamblam points out, you're defining an array when you should be making an object.

Comments

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.