Thank for the quick answers & yep as you guys pointed out it was an issue with the initial value. Also, following your suggestions I switched to using map and am now using,
const q = Object.entries(query).map(
([key, val]) => `${key}=${encodeURIComponent(val)}`).join('&');
=========
Note: I am posing this question more out of curiosity because I ended up finding an alternative solution.
I have a query object
{
artist: 'Jon Bellion',
title: 'Kingdom Come'
}
and want to turn this into the string artist:Jon+Bellion&title:Kingdom+Come
. My first attempt at this was to try to use reduce on the entries of the object as seen below.
const query = { artist: 'Jon Bellion', title: 'Kingdom Come' };
let q = Object.entries(query).reduce(
(str, [key, val]) => `${str}&${key};${val}`
);
q = q.replace(/\s/g, '+');
console.log(q);
This code results in artist,Jon+Bellion&title:Kingdom+Come
. It is so close but for some reason there is a ,
instead of a :
between artist
and Jon
.
I ended up switching to
let str = '';
Object.entries(query).forEach(
([key, value]) => (str += `${key}:${value}&`),
);
const q = str.replace(/\s/g, '+').slice(0, -1);
console.log(q);
Which gives me the desired result, artist:Jon+Bellion&title:Kingdom+Come
.