Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript associative array to JSON

How can I convert a JavaScript associative array into JSON?

I have 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: "[]"
like image 273
ActionOwl Avatar asked Dec 13 '10 02:12

ActionOwl


3 Answers

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.length
0

What is often referred to as "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"}"

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'].

like image 173
Felix Kling Avatar answered Nov 09 '22 01:11

Felix Kling


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.

like image 43
AndreKR Avatar answered Nov 09 '22 01:11

AndreKR


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);
like image 5
killer_kohlrabi Avatar answered Nov 09 '22 02:11

killer_kohlrabi