0

I've an URL where the query string parameters are dynamic. I need to read them in my JavaScript. What I've done is

I've used the following code to read all the query string parameters.

For example:

// given url http://example.com/#/some/path?foo=bar&baz=xoxo
var searchObject = $location.search();
// searchObject  => {foo: 'bar', baz: 'xoxo'}

I also have an array with the keys. Here my array will have foo and baz.

For example: var list = ["foo", "baz"];

So how do I get the values from the URL with the keys I've in my list array?

I tried this way

for(var i=0; i<list.length; i++)
                {
                    alert(searchObject.list[i]);
                }

But this gave me an Error in the console searchObject.list is undefined.

What am I doing wrong here? Can someone help?

3 Answers 3

1

This should be what you want:

for(var i=0; i<list.length; i++) {
    alert(searchObject[list[i]]);
}

Loop though the items of list, using each one as the key to the searchObject object.

http://jsfiddle.net/8vekqezj/

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

Comments

1

May be using the AngularJS utility:

angular.forEach(list, function(key){
  alert(searchObject[key]);
});

Comments

1

Try

for(var i=0; i<list.length; i++)
{
    alert(searchObject[list[i]]);
}

I'm not sure why you have included the list property, searchObject is just and (as the name suggests) a plain old javascript object.

2 Comments

searchObject is (as you say) a plain old javascript object. So why are you indexing into it with the indexes of the list array?
You're right, my bad ;) now we have the same solution :D

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.