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.
rData = [ 100 : ..is already invalid. And why would you want to put every single value in an array? That makes accessing the data so much more difficult. JavaScript doesn't have associative arrays, but you can use objects askey -> valuemap. What's wrong with the existing data structure, i.e. the way how the JSON is structured? Do you just want to create a mapid -> object? Please explain the problem you are actually trying to solve.obj.response, is a JavaScript array. How you obtained the data (i.e. as JSON) is irrelevant to what you are trying to do.obj.responseinstead of converting it into an array. I'll do some experiments on my end and will accept answer later on. Thanks for the help.id -> objectmapping, directly usingobj.responseis of course the easiest approach.