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
Can Es6 Template Literals Be Substituted at Runtime (Or Reused)
How to Use Onclick() or Onselect() on Option Tag in a Jsp Page
JavaScript - How to Detect If Document Has Loaded (Ie 7/Firefox 3)
What Is Returned from a Constructor
iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari
How to Destructure Object Properties with Key Names That Are Invalid Variable Names
Converting .Net Datetime to JSON
Programmatically Open New Pages on Tabs
How to Find the Height of Text on an HTML Canvas
Idiomatically Find the Number of Occurrences a Given Value Has in an Array
How to Convert Date to Timestamp
Using Http Rest APIs with Angular 2
Difference Between "Change" and "Input" Event for an 'Input' Element
Create Svg Tag with JavaScript
Remove Not Alphanumeric Characters from String
Need to Escape a Special Character in a Jquery Selector String
Is There a Built-In Way to Loop Through the Properties of an Object