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];
  });
  • And take a look at how to use [this](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) in js. – Serge Seredenko Feb 02 '18 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. – noahnu Feb 02 '18 at 16:12

2 Answers2

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];
  });
Andreas
  • 21,535
  • 7
  • 47
  • 56
developer
  • 690
  • 7
  • 16
  • 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 –  Feb 02 '18 at 16:21
  • @AdamGusky `{}` is an object and not an array (`[]`) – Andreas Feb 03 '18 at 10:09
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);
Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67