Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Best way to convert associative array to string and back the other way later?

Tags:

I have an associative array as follows:

var AssocArray = { id:0, folder:'Next', text:'Apple' };

Now I need to store this in a database, so I figure I would just convert this into a string, store it in the database and then pull it out of the database and put it back into a javascript array later on.

The catch is that the actual # of items, and the array variables will be different every time (hence why I wanted to store it as one long string instead).

What’s the best way to convert this associative array into a string, and then also vice versa, how to convert a string into an associative array?

like image 955
Mark Avatar asked Jan 21 '13 00:01

Mark


People also ask

Which method is used to convert arrays to strings in JavaScript?

JavaScript Array toString() The toString() method returns a string with array values separated by commas. The toString() method does not change the original array.

What is the best way to turn an array into an object using JavaScript?

To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result. Copied!

Which Javacript method is use to convert a string into an array of substrings?

The split() method splits a string into an array of substrings. The split() method returns the new array.


Video Answer


1 Answers

There is nothing better than JSON for it:

var str = JSON.stringify(obj);
// >> "{"id":0,"folder":"Next","text":"Apple"}"

var obj = JSON.parse(str);
// >> Object({ id: 0, folder: "Next", text: "Apple" })
like image 73
VisioN Avatar answered Oct 01 '22 07:10

VisioN