I am trying to make a script which
- Gets the current URL (url1 variable in the example) which contains params/values and which can be entirely different each time – OK
- I extract both params and values and create an object from them with keys/values – OK
- 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
The
URLToArray()
returns an object and not an array. You cannot useforEach
on an instance of an object.Instead, you may want to iterate over keys, like the following:
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.
Consider the following.
This does not do anything vastly different, it just makes a bit better use of the tools at hand to get the same result.