Reputation: 1011
I'm trying to fill array with JSON response. JSON response from ajax is:
[{"id":"1","category":"Chloting"},{"id":"2","category":"Shoes"},{"id":"3","category":"Jewelry and Watches"},{"id":"4","category":"Accessories"}]
My code is folowing:
var categories = [];
$('body').on("click", '.category_editable', function(){
$.ajax({
type:"get",
dataType: "json",
url:"ajax_php/get_all_categories.php",
success:function(data){
$.each( data, function( i, itemData ) {
categories[i] = itemData.category;
});
console.log(categories);
}
});
});
And what I'm getting is array without keys, because I don't know how to push them into array:
["Chloting", "Shoes", "Jewelry and Watches", "Accessories"]
But I need to will it in object format like this:
["1":"Chloting", "2":"Shoes", "3":"Jewelry and Watches","4":"Accessories"]
Upvotes: 0
Views: 71
Reputation: 3373
var jsondata=[{"id":"1","category":"Chloting"},{"id":"2","category":"Shoes"},{"id":"3","category":"Jewelry and Watches"},{"id":"4","category":"Accessories"}];
var categories={};
$.each( jsondata, function( i, itemData ) {
categories[itemData.id] = itemData.category;
});
console.log(categories);
Upvotes: 0
Reputation: 1669
$(function(){
var d={};
var results=[
[{"id":"1","category":"Chloting"},{"id":"2","category":"Shoes"},{"id":"3","category":"Jewelry and Watches"},{"id":"4","category":"Accessories"}]
];
$.each(results[0],function(k,v)
{
//alert(k+' '+v.id);
//alert(v.id+' '+v.category);
d[v.id]=v.category;
});
alert(JSON.stringify(d));
$("#output").html(JSON.stringify(d));
});
Upvotes: 0