Convert JSON to Associative array

arrays, javascript, json

Solution

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" 
    }
}

Problem

I want to convert a JSON response to associative array but looks like I was not able to make it right. Here is my JSON sample response: ``` { "response":[ { "id":100, "certificate":{ "id":1, "title":"Lorem ipsum dolor sit amet, consectetur adipiscing elit." }, "created_at":"2013-12-02T15:20:08.233Z" }, { "id":101, "certificate":{ "id":2, "title":"Aenean facilisis, nisl vitae pulvinar varius." }, "created_at":"2013-12-02T15:20:08.240Z" } ], "count":2 } ``` This is what I have tried so far: ``` var len = obj.response.length; var rData = []; var gcData = []; for(var i = 0; i < len; i++){ rData[i] = $.map(obj.response[i], function(value, index) { if(typeof value=="object"){ gcData = $.map(value, function(value1, index) { return [value1]; }); return gcData; }else{ return [value]; } }); } ``` My expected output: ``` rData = [ 100 : [ id: ["100"], certificate: [ id: ["1"], title: ["Lorem ipsum dolor sit amet, consectetur adipiscing elit."] ], created_at: ["2013-12-02T15:20:08.240Z"] ] 101 : [ id: ["101"], certificate: [ id: ["2"], title: ["Aenean facilisis, nisl vitae pulvinar varius."] ], created_at: ["2013-12-02T15:20:08.240Z"] ] ] ``` Please help. Thanks.

Original source