0

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.

thefinnomenon
  • 1,223
  • 9
  • 14

1 Answers1

3

You didn't pass an initial value to reduce, so the initial value is taken to be the first entry, which is

['artist', 'Jon Bellion']

On the first (and only) iteration of reduce, it's turned into a string:

`${str}

Which means that the items in the array get joined by a comma:

'artist,Jon Bellion'

Either pass an initial value of the empty string:

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, '+').slice(1);
console.log(q);

Or use .map instead, which is a better idea IMO, since each segment of the generated string can then be joined by &, which is nicer than slicing the first & off:

const query = { artist: 'Jon Bellion', title: 'Kingdom Come' };

const strs = Object.entries(query).map(([key, val]) => `${key}:${val}`);
console.log(strs.join('&').replace(/\s/g, '+'));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320