Somethingwhatever
Somethingwhatever

Reputation: 1348

How to create a string query in javascript?

i was given a homework problem to be able to create a query string based on certain parameters in an array? I am still fairly new to javascript so have some success with it but would appreciate if someone can check my code please. Thank you to everyone in advance.

I am using forEach to loop through the array to get the values and using string concatenation to get some url. I have made a sample codepen for it.

https://codepen.io/anon/pen/pmRXzg

let Person = {
  name: ['Sam', 'Daisy'],
  food: ['banana', 'Apple']
}

let handler = Object.entries(Person)

handler.forEach(function(element) {
  console.log(element)
})

let myUrl = Object.entries(handler).map(key => key + '=' +
  handler[key]).join('&')
let visitUrl = "http://someURLString/?" + myUrl
console.log(myUrl)
console.log(visitUrl)

How can i get my final result to look like

someUrlString/?name=Sam,Daisy&food=banana,apple

Upvotes: 2

Views: 66

Answers (2)

Maheer Ali
Maheer Ali

Reputation: 36574

You can use map() on Object.entries() and then join() entries by = and then join result by &

let Person = {
   name: ['Sam','Daisy'],
  food: ['banana','Apple']
 }
 
let res = Object.entries(Person).map(x=> x.join('=')).join('&');

console.log(res)

Explanation:

Object.entiries() return an array of arrays. Each array contain key value pair. In this case entries will be [['name', ['Sam','Daisy']], ['food', ['banana','Apple']]].

Now we use map() on array. map() is takes a callback. It that callback first argument(in above case its x) is current element of array through which we are iterating. map() creates new array of same length based on the value returned from callback. In above case value returned is x.join('=')

join() is method which converts array to string by adding a given substring b/w each of them. So when apply join() on

[food , ['banana','Apple']].join('=')

it will become

"food=banana,Apple"

The array ['banana','Apple'] is converted to a string implicitly. So ['banana','Apple'] is banana,Apple

In the last part we get array ["name=Sam,Daisy","food=banana,Apple"] and we join() it by &.

The point is that when we array is converted to string. It returns string in which all elements are separated by ,

Upvotes: 3

briosheje
briosheje

Reputation: 7446

You can take advantage of .entries, .map and .join to:

  • Map [key,value] pairs of Person.
  • Transform their value to a single string, by eventually manipulating data.
  • Join them to return the final string.

let Person = {
  name: ['Sam', 'Daisy'],
  food: ['banana', 'Apple']
}

const res = Object.entries(Person).map(([entryName, entryValues]) => {
  return `${entryName}=${entryValues.map(i => i.toLowerCase()).join(',')}`;
}).join('&');

const url = `someUrlString/?${res}`;

console.log(url);

Upvotes: 2

Related Questions