[英]Display objects from an array in order, depending on an specific value
i have this json: 我有这个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}
];
I am displaying them in order with something like this: 我按如下顺序显示它们:
for (var i = 0 ; i <proj_num; i++){
var numClass="p_"+projects_array[i].index;
var act="<li class='"+numClass+"'></li>";
$('#lookfor').append(act);
}
What i need now is to display first all the objects with the value "a" in the category attribute and then all the other objects in any order, i tried using .sort() in this way:\\ 我现在需要的是首先在category属性中显示所有值为“ a”的对象,然后按任何顺序显示所有其他对象,我尝试以这种方式使用.sort():\\
function compare(obj){
if(obj.category == "a"){ return 1;}
else{return 0;}
}
obj.sort(compare);
But it does not worked because it kind of group all the objects of the category... 但这是行不通的,因为它将某种类别的所有对象归为一类。
do you have any possible solution for this problem? 您对此问题有什么解决方案吗?
ps: I tried to simplify my code to make it understandable, i hope it be clear for you, thanks in advance ps:我试图简化代码以使其易于理解,我希望对您来说清楚一点,在此先感谢
this will sort according to the important word first. 这将首先根据重要单词进行排序。
http://jsbin.com/umezet/12/edit 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']);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.