0

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

3 Answers 3

1

Change

var categories = [];

to

var categories = {};
Sign up to request clarification or add additional context in comments.

Comments

0
$(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/

1 Comment

Im i getting undefined in console log. I've passed [itemData.id] instead of [i], and data[0] instead of data only in each function
0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.