拥有一个非常大的对象集合,如下所示:
[
{
"name": "john",
"job": "cop",
"city": "london"
},
{
"name": "mike",
"job": "nurse",
"city": "las vegas"
},
{
"name": "kate",
"job": "teacher",
"city": "london"
}
]
我试图按city
的顺序迭代它们。伪代码:
For each city
print some extra city info
For each person in city
print person info
next
print some other extra city info
next
我知道如何以复杂的方式做到这一点;使用JQuery有一个简单的吗?
答案 0 :(得分:1)
首先按城市排序信息:
info.sort(function(i1, i2{
if (i1 < i2) {
return 1;
} else if (i1 > i2) {
return -1;
} else {
return 0;
}
});
然后迭代元素,随时更改城市信息。
var last_city = null;
$.each(info, function(i, el) {
if (el.city != last_city) {
// print extra city info
}
// print person info
if (el.city != last_city) {
// print more city info
last_city = el.city;
}
});