skip to Main Content

I am trying to make a script which

  1. Gets the current URL (url1 variable in the example) which contains params/values and which can be entirely different each time – OK
  2. I extract both params and values and create an object from them with keys/values – OK
  3. I build a condition for later use, dynamically which does not expect a certain number of pairs, so it gets built from whatever it finds in the object – NOT OK

.

let url1 = 'http://localhost/myproject/results?id=0001&area=eiffel+tower&city=Paris&whatever=else';

function URLToArray(url) {
    var request = {};
    var pairs = url.substring(url.indexOf('?') + 1).split('&');
    for (var i = 0; i < pairs.length; i++) {
        if(!pairs[i])
            continue;
        var pair = pairs[i].split('=');
        request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
     }
     console.log(request); // { id: '0001', area: 'eiffel+tower', city: 'Paris', whatever: 'else' }
     return(request);
}

let paramsObj = URLToArray(url1);

console.log(paramsObj)  // { id: '0001', area: 'eiffel+tower', city: 'Paris', whatever: 'else' }

// Step 3 below, where the issue is and I expect
// id === '0001' && area === 'eiffel+tower' && city === 'Paris' && something === 'else'

paramsObj.forEach((item) => {
  let condition = '';
  let keys = Object.keys(item);
  keys.map((k) => {
    if (condition) {
      condition += ` && ${k} === '${item[k]}'`
} else {
  condition = `${k} === '${item[k]}'`
    }

  })
  console.log(condition);
})

Outputs

paramsObj.forEach((item) => { TypeError: paramsObj.forEach is not a function at Object.<anonymous>

Expected on console.log(condition)

id === '0001' && area === 'eiffel+tower' && city === 'Paris' && whatever === 'else'

Note: if the object was inside [ ] brackets, the output would somehow be the expected one. However URLToArray(url) outputs object without brackets.

3

Answers


  1. The URLToArray() returns an object and not an array. You cannot use forEach on an instance of an object.

    Instead, you may want to iterate over keys, like the following:

    Object.keys(paramsObj).forEach((key) => {
      const value = paramsObj[key];
      let condition = '';
      if (condition) {
        condition += ` && ${key} == ${value}`;
      } else {
        condition = `${key} == ${value}`;
      }
    );
    
    Login or Signup to reply.
  2. ForEach method is an array method and you’re trying to use it on an object, you should probably just create a function that takes in an object as one of its parameters.

    function ProcessItem(item) {
      let condition = '';
      let keys = Object.keys(item);
      keys.map((k) => {
        if (condition) {
          condition += ` && ${k} === '${item[k]}'`
        } else {
          condition = `${k} === '${item[k]}'`
        }
    
      })
      console.log(condition);
    }
    Login or Signup to reply.
  3. Consider the following.

    var url1 = 'http://localhost/myproject/results?id=0001&area=eiffel%20tower&city=Paris&whatever=else';
    
    function getQueryFromURL(u) {
      var r = {};
      var parts;
      if (u.indexOf("?") > -1) {
        parts = u.substr(u.indexOf("?") + 1).split("&");
        $.each(parts, function(i, v) {
          r[v.split("=")[0]] = decodeURI(v.split("=")[1]);
        });
      }
      return r;
    }
    
    function objJoin(o, a, b) {
      var r = "";
      var arr;
      $.each(o, function(k, v) {
        if (r.length == 0) {
          r += [k, a, v].join(" ");
        } else {
          r += " " + [b, k, a, v].join(" ");
        }
      });
      return r;
    }
    
    let paramsObj = getQueryFromURL(url1);
    
    console.log(paramsObj);
    
    console.log(objJoin(paramsObj, "===", "&&"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    This does not do anything vastly different, it just makes a bit better use of the tools at hand to get the same result.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search