Search code examples
javascriptjavascript-objects

How can I customize my object's property names with specific variable values without hardcoding them?


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];
  });

Solution

  • 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];
      });