2

我有这个json:

var projects_array = [
{name:"proj1", category:"a", index:1},

{name:"proj2", category:"a", index:2},

{name:"proj3", category:"b", index:3},  

{name:"proj4", category:"c", index:4}
];

我正在按顺序显示它们,如下所示:

for (var i = 0 ; i <proj_num; i++){ 
var numClass="p_"+projects_array[i].index;  
    var act="<li class='"+numClass+"'></li>";           
$('#lookfor').append(act);             
}

我现在需要的是首先显示类别属性中值为“a”的所有对象,然后以任何顺序显示所有其他对象,我尝试以这种方式使用 .sort():\

 function compare(obj){
if(obj.category == "a"){ return 1;}                 
    else{return 0;}                     
}                       
obj.sort(compare);

但它不起作用,因为它将类别的所有对象分组......

您对此问题有任何可能的解决方案吗?

ps:我试图简化我的代码以使其易于理解,我希望它对你来说很清楚,在此先感谢

4

1 回答 1

0

这将首先根据重要词排序。

http://jsbin.com/umezet/12/edit

     var projects_array = [
{
    name: "proj1",
    category: "action",
    index: 1
}, {
    name: "proj2",
    category: "time",
    index: 2
}, {
    name: "proj3",
    category: "buu",
    index: 3
}, {
    name: "proj3",
    category: "time",
    index: 3
}, {
    name: "proj4",
    category: "cooo",
    index: 4
}, {
    name: "proj3",
    category: "@",
    index: 3
}, {
    name: "proj1",
    category: "!",
    index: 1
}, {
    name: "proj2",
    category: "%",
    index: 2
}, {
    name: "proj3",
    category: "cooo",
    index: 3
}, {
    name: "proj4",
    category: "*",
    index: 4
}];
projects_array = projects_array.sort(

function (x, y)
{
    if(x['category'] == 'time') return -1;
    if(y['category'] == 'time') return 1;
    if(x['category'] > y['category']) return 1;
    if(x['category'] < y['category']) return -1;
    return 0;
});
for(var i = 0; i < projects_array.length; i++)
{
    $('body').append(projects_array[i]['category']);
}
于 2012-05-10T07:52:10.107 回答