fingers10
fingers10

Reputation: 7977

How to convert array of object to uri encoded querystring in typescript

I'm new to typescript. I have a input array like this,

filter = [
  {
    field : "eventId",
    value : "123"
  },
  {
    field : "baseLocation",
    value : "singapore"
  }
]

I need this array of objects to be like,

..test.com?search=eventid%20eq%20123&search=baselocation%20eq%20singapore

I tried like this, but nothing happens,

    var test = '';

    if (filter != undefined && filter.length > 0)
      filter.array.forEach(item => {
        test += Object.keys(item).map(k => `${k}=${encodeURIComponent(item[k])}`);
      });

    console.log(test);

console log is always empty. Can this be done in a better way?

Please note that i need all field values in lower case instead of camelcase. Please assist.

Upvotes: 2

Views: 313

Answers (1)

ggorlen
ggorlen

Reputation: 57106

The filter.array.forEach statement is problematic; since array is an undefined property, calling forEach on it leads to a crash. Beyond that, some of your desired formatting components such as the %20eq%20 substrings and lowercasing are missing.

Here's an approach that emits expected output using array.map; you can index right into the object since there are only two properties:

const filter = [
  {
    field : "eventId",
    value : "123"
  },
  {
    field : "baseLocation",
    value : "singapore"
  }
];

const expected = `..test.com?search=eventid%20eq%20123&search=baselocation%20eq%20singapore`;

const actual = `..test.com?${filter.map(o =>
  `search=${o.field}%20eq%20${o.value}`
).join`&`.toLowerCase()}`;

console.log(actual === expected, actual);

Upvotes: 1

Related Questions