Associative JavaScript Array for JSON

How to convert associative javascript array to json?

I tried the following:

var AssocArray = new Array(); AssocArray["a"] = "The letter A" console.log("a = " + AssocArray["a"]); // result: "a = The letter A" JSON.stringify(AssocArray); // result: "[]" 
+68
json javascript associative-array
Dec 13 '10 at 2:01
source share
5 answers

Arrays should only have entries with numeric keys (arrays are also objects, but you should not mix them).

If you convert the array to JSON, the process will only consider numeric properties. Other properties are simply ignored and therefore you get an empty array. Perhaps this is more obvious if you look at the length array:

 > AssocArray.length 0 

What is often called an "associative array" is actually just an object in JS:

 var AssocArray = {}; // <- initialize an object, not an array AssocArray["a"] = "The letter A" console.log("a = " + AssocArray["a"]); // "a = The letter A" JSON.stringify(AssocArray); // "{"a":"The letter A"}" 

Access to the properties of objects can be obtained using notation or dot notation of the array (if the key is not a reserved keyword). Thus, AssocArray.a same as AssocArray['a'] .

+126
Dec 13 '10 at 2:03
source share

JavaScript has no associative arrays. However, there are objects with named properties, so just don’t initialize your β€œarray” with new Array , then it will become a universal object.

+7
Dec 13 2018-10-12T00:
source share

Agreed that it is probably best to store objects as objects and arrays as arrays. However, if you have an object with named properties that you treat as an array, here's how to do it:

 let tempArr = []; Object.keys(objectArr).forEach( (element) => { tempArr.push(objectArr[element]); }); let json = JSON.stringify(tempArr); 
+2
Dec 04 '17 at 18:00
source share

I posted a fix for this here

You can use this function to modify JSON.stringify to encode arrays , just place it near the beginning of your script (see the link above for more details):

 // Upgrade for JSON.stringify, updated to allow arrays (function(){ // Convert array to object var convArrToObj = function(array){ var thisEleObj = new Object(); if(typeof array == "object"){ for(var i in array){ var thisEle = convArrToObj(array[i]); thisEleObj[i] = thisEle; } }else { thisEleObj = array; } return thisEleObj; }; var oldJSONStringify = JSON.stringify; JSON.stringify = function(input){ if(oldJSONStringify(input) == '[]') return oldJSONStringify(convArrToObj(input)); else return oldJSONStringify(input); }; })(); 
+1
Jul 14 '14 at 2:27
source share

You can push an object into an array

 enter code here var AssocArray = new Array(); AssocArray.push( "The letter A"); console.log("a = " + AssocArray[0]); // result: "a = The letter A" console.log( AssocArray[0]); JSON.stringify(AssocArray); 
-one
Sep 04 '12 at 16:29
source share



All Articles