Monthly Archives: October 2012

JavaScript List to Array and Array to List

Sometimes we don’t know about all functionality of any technology. So normally we have made whole logic for our requirement. The same case occurred with me and I want share with you.

Actually, I wanted to convert my JavaScript Array into List. Just look below code that I have made before some days in order to Array to List in JavaScript.

Custom code for convert Array to List in JavaScript.

Today during googling I got in-built JavaScript function that converts automatically Array to List and I said to myself OMG. Yes, you are thinking absolutely correct. It’s the join().

join() // Convert JavaScript array to list.

 

tArr = [“One”,”Two”,”Three”,”Four”,”Five”,”Six”,”Seven”];
tList = tArr.join();

You can see it’s reduce almost 70% line code and programming time as well. Most of the programmer use to with this type of stuff and as always its part of programming.

The same thing for convert JavaScript list to array and It’s split() function but that I know. I always use split() function for conversion. :)

split([delimiter]) // Convert JavaScript list to array.

tList = “One,Two,Three,Four,Five,Six,Seven”;
tArr = tList.split(‘,’);

Hope you enjoy with this stuff and put comment if you have faced this type of stuff in any language.

Convert JSON object to URL Query String?

In today’s era Ajax and JSON become more and more popular day by day as noone wants to waste their time and wants everything immediately as soon as possible at one place.

Short explanations about Ajax and JSON.

Ajax (Asynchronous JavaScript and XML) is a method to retrieve data or change Dom object without refreshing page or we can say do user request immediately.

JSON (JavaScript Object Notation) is nothing but just a pair of key and value. Example {“Key” : “Value”, …..}.

What I want to say?

Guess, We have JSON object like

{‘firstname’:’Bharat’, ‘lastname’:’patel’,’hobby’:’write blog’,’blogurl’:’sourcecodemart.com’}

And convert it as URL Query String like

“firstname=Bharat&lastname=patel&hobby=write+blog&blogurl=sourcecodemart.com”

Sometimes we have JSON object as like above and wants to send request via Ajax to server in query string so that we must have to build procedure to covert JSON object to Query String.

Don’t worry as we have jQuery. We know our work has been reduced if use jQuery. Here taking about $.param() function of jQuery. It converts JSON object to Query String.

jQuery.param(JSON OBJECT);

Example:

var obj = {‘firstname’:’Bharat’, ‘lastname’:’patel’,’hobby’:’write blog’,’blogurl’:’sourcecodemart.com’};

var queryString = jQuery.param(obj);

console.log(queryString);

Output seems like:

firstname=Bharat&lastname=patel&hobby=write+blog&blogurl=sourcecodemart.com

For more details about jQuery.param() click here.