2

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.

2
  • 1
    Would something like this be useful? filter.map(a => 'search=' + encodeURIComponent(a.field.toLowerCase() + '=' + a.value.toLowerCase())).join('&') Commented Mar 12, 2019 at 2:37
  • Thanks man. This is much simpler than the below answer Commented Mar 12, 2019 at 2:54

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.