21

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?

MySky
  • 161
  • 1
  • 19
Mark
  • 3,653
  • 10
  • 30
  • 62
  • Btw, in JavaScript all objects are associative arrays. – Šime Vidas Jan 21 '13 at 00:19
  • 1
    To be clear on terminology, JS does not have associative arrays like PHP does. What your code shows is an Object with properties. Language-wise, this JS is closer to `$obj = new stdClass(); $obj->id = 0; ...`. You can generally convert them back and forth, but calling them associative arrays is incorrect. – loganfsmyth Jan 21 '13 at 00:19
  • @loganfsmyth In JavaScript, all objects are *de facto* associative arrays, are they not? The ECMAScript specification does not use the term "associative array" afaik, but the way objects are spec'd, they are associative arrays in practice. – Šime Vidas Jan 21 '13 at 00:21
  • 2
    @ŠimeVidas Kind of, I just think that thinking of JS objects like associative arrays can cause logic errors and generally make people more likely to write code that breaks. When working with objects you always need to take the prototype chain into account and thinking of objects as a flat store of key->value pairs ignores that. – loganfsmyth Jan 21 '13 at 00:25
  • @loganfsmyth Yup. Good point. – Šime Vidas Jan 21 '13 at 00:52

1 Answers1

46

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" })
VisioN
  • 143,310
  • 32
  • 282
  • 281