I am attempting to create a string that is used with HTML. But the scope of what I am attempting is completed in javascript. My code is not returning the way my mentor has desired, so I am at a bit of loss.
My function is called toQueryString
, which accepts an object and returns a string with each key and value separated by a =
and each pair separated by a &
. If the value is an array, add another pair to the string with each value.
My code is:
function toQueryString(obj) {
var key = Object.keys(obj);
var value = Object.values(obj);
var result = ``;
for (let i = 0; i < key.length; i++) {
for (let j = 0; j < value.length; j++) {
result += key[i] += `=` + value[j] + `&`;
}
}
return result;
}
toQueryString({"bar": [ 2, 3], "foo": 1 }) // "bar=2&bar=3&foo=1"
This returns:
'bar=2,3&bar=2,3&=1&foo=2,3&foo=2,3&=1&'
but should return this:
bar=2&bar=3&foo=1
Can anyone help me figure out what is broken?