2

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
2
  • 6
    FYI, if your code works and you are seeking improvements, CodeReview is the site for it Commented May 16, 2019 at 13:58
  • @AndreiGheorghiu I really appreciate the help but i was actually able to figure it out. Thank you so much. If you want to, you can go ahead and delete it. Commented Jun 16, 2019 at 20:47

2 Answers 2

3

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 ,

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

5 Comments

thank you so much. this was what i needed. Could you please explain how this works? that would help me for future references. And how it is different than template strings?
Entries get each key and value and places them in an array, for example the first entry would be this: ['name', ['sam', 'daisy'] Then .map() is like a for loop, except it returns an array of items from the callback function. Here Maheer has used x as an identifier for each entry. So, he uses .join() to join the items in the array, delimited by an =, which results in name=Sam,Daisy. Then this same function happens for each of the other entries, then he ends it with another .join(). So, he will join the new entries with a &, resulting in name=Sam,Daisy&food=banana,Apple
@KobanDavis ohhh i see . damnn you guys are really good lol. Thank you.
You'll get there in no time. Understanding why a function works is the only way to learn, so keep it up 👍
@paaswhatever I have added a detailed explanation make sure to see it.
2

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

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.