JavaScript Associative Array to 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.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'].

Retrieving and using a json associative array

As i mentioned in comments, php associative arrays become javascript objects, which cant be accessed numericaly.

A solution would be to send an array of objects instead:

while ($row = $stmt->fetch_assoc()) {

$json[]= ['key'=>'item_'.$row['id'] , 'value' => $row['name']];
}

the in js:

data[0].key;
data[0].value;

EDIT obviously key is a misleading name in this example, better to call it something else:

$json[]= ['id'=>'item_'.$row['id'] , 'value' => $row['name']];
//js
data[0].id;

Convert JSON to Associative array

I just want to group it by keys something like I have in expected output

It seems you want to create an id -> object map. To do that you just have to iterate over the array, take the id attribute of each object as property name and assign the object (the element of the array) to that property of the map.

Example:

var map = {};
var response = obj.response;

for (var i = 0, l = response.length; i < l; i++) {
map[response[i].id] = response[i];
}

console.log(map);

Each object inside the array is already in the structure you want it to be. The output is

{
"100": {
"id": 100,
"certificate": {
"id": 1,
"title": "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
},
"created_at": "2013-12-02T15:20:08.233Z"
},
"101": {
"id": 101,
"certificate": {
"id": 2,
"title": "Aenean facilisis, nisl vitae pulvinar varius."
},
"created_at": "2013-12-02T15:20:08.240Z"
}
}

Convert JSON Object array into associative array

You could use an object and iterate the array with Array#forEach

The forEach() method executes a provided function once per array element.

and assign the element to the property with the name of a.ResourceId.

The callback uses an Arrow function, because there is only one assignment.

var data = [{ "DefinitionId": 193041, "ResourceId": -2147290607, "AssetId": 193041 }, { "DefinitionId": 193042, "ResourceId": -2147290603, "AssetId": 193042 }],    object = {};
data.forEach(a => object[a.ResourceId] = a);
console.log(object);


Related Topics



Leave a reply



Submit