0

I am creating a URL Parser for a school project. I first parse the full query from the url into an array, since query members are separated by "&".

var queryString = /\?(\&?\w+\=\w+)+/.exec(urlString))[0].split("&");

Each array member would look like:

arr[i] = "field=value";

I am doing this in an Object constructor in which I need to return an "HTTPObject". For the assignment, the HTTPObject must have a property called "query", and query should have many properties (one for each query field in the url). Why doesn't this work?

queryString.forEach(function(element) {
    var elementArr = element.split("=");
    this.query.elementArr[0] = elementArr[1];
  });
2
  • And take a look at how to use this in js. Commented Feb 2, 2018 at 16:12
  • If your code worked, how would you differentiate this.query."field" from this.query.elementArr = []? i.e. your approach attempts to access an element on an array with a key "elementArr" on the query object. Commented Feb 2, 2018 at 16:12

2 Answers 2

0

you cannt set a property like that - but you can with bracket notation:

try this

queryString.forEach(function(element) {
    var elementArr = element.split("=");
    this.query[elementArr[0]] = elementArr[1];
  });
Sign up to request clarification or add additional context in comments.

2 Comments

This worked after I created an array (var query = {}), set it's values with the foreach, then set this.query to that array I just created. Thanks
@AdamGusky {} is an object and not an array ([])
0

You were very close. You can refer to object properties by name, using square brackets...

var queryString = ["name1=value1", "name2=value2"];
var query = {};

queryString.forEach(function(element) {
    var elementArr = element.split("=");
    query[elementArr[0]] = elementArr[1];
});

var varName = "name1";

console.log("by variable : " + query[varName]);  // can use a variable
console.log("by string   : " + query["name1"]);  // can use a string
console.log("by propname : " + query.name1);     // can hardcode the property name
console.log("query object:");
console.log(query);

Comments