如何用json对象填充jquery数组

时间:2014-04-18 10:49:33

标签: jquery

我试图用JSON响应来填充数组。来自ajax的JSON响应是:

[{"id":"1","category":"Chloting"},{"id":"2","category":"Shoes"},{"id":"3","category":"Jewelry and Watches"},{"id":"4","category":"Accessories"}]

我的代码如下:

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

我得到的是没有钥匙的阵列,因为我不知道如何将它们推入阵列:

["Chloting", "Shoes", "Jewelry and Watches", "Accessories"]

但是我需要这样的对象格式:

["1":"Chloting", "2":"Shoes", "3":"Jewelry and Watches","4":"Accessories"] 

3 个答案:

答案 0 :(得分:1)

更改

var categories = [];

var categories = {};

答案 1 :(得分: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/

答案 2 :(得分: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