Munez NS
Munez NS

Reputation: 1011

How to fill jquery array with json object

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

Answers (3)

Tuhin
Tuhin

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);

DEMO FIDDLE

Upvotes: 0

jignesh
jignesh

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));
});

http://jsfiddle.net/vAVQk/

Upvotes: 0

James M
James M

Reputation: 16728

Change

var categories = [];

to

var categories = {};

Upvotes: 1

Related Questions