Skip to content Skip to sidebar Skip to footer

How To Stringify An Array In Javascript?

I am running the following piece of code: var arr = []; arr['aaa'] = { 'xxx' : 1, 'ttt' : 2 }; arr['bbb'] = { 'xxx' : 5, 'qqq' : 6 }; var tmp = JSON.stringify(ar

Solution 1:

Use

var arr = {};

Arrays should only be used for numerically indexed data, not arbitrary properties. Of course you are able to do it, because they are, in fact, objects. But it won't work in JSON.

Instead, just use objects.

Solution 2:

You can't do that, for two reasons:

  • The stringify method only consider the data in the array, not properties.
  • There is no JSON format for an array with properties.

If you want the representation of an array in the JSON, you need to put the data in the actual array, not as properties in the array object.

If you want the properties in the JSON, you need to use a plain object instead of an array.

Post a Comment for "How To Stringify An Array In Javascript?"