JavaScript associative array to JSON JavaScript associative array to JSON json json

JavaScript associative array to JSON


Arrays should only have entries with numerical keys (arrays are also objects but you really should not mix these).

If you convert an array to JSON, the process will only take numerical properties into account. Other properties are simply ignored and that's why you get an empty array as result. Maybe this more obvious if you look at the length of the array:

> AssocArray.length0

What is often referred to as "associative array" is actually just an object in JS:

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

Properties of objects can be accessed via array notation or dot notation (if the key is not a reserved keyword). Thus AssocArray.a is the same as AssocArray['a'].


There are no associative arrays in JavaScript. However, there are objects with named properties, so just don't initialise your "array" with new Array, then it becomes a generic object.


Agreed that it is probably best practice to keep Objects as objects and Arrays as arrays. However, if you have an Object with named properties that you are treating as an array, here is how it can be done:

let tempArr = [];Object.keys(objectArr).forEach( (element) => {    tempArr.push(objectArr[element]);});let json = JSON.stringify(tempArr);