我正在尝试显示从我的数据库返回的记录
我的返回数据如下:
UserID Username Fullname ID
141 john jerry1 170
141 john jerry1 18
141 john jerry1 1169
110 ted jerrytest 1701
110 ted jerrytest 18
我想在页面中显示所有ID,但要避免重复的用户名
所以它就像
john 170
18
1169
ted 1701
18
//I only want 2 divs (for john and ted) instead of 5.
我的代码目前显示
john 170 //1 loop
john 18 //1 loop
john 1169 //1 loop
ted 1701 //1 loop
ted 18 //1 loop
我的代码:
for(var i=0; i<results.length; i++){
//create a div for each row...in my case, 5 divs/rows
//i tried to create a var a
a=i-1;
if(results[a]){
if(results[i].Username==results[a].Username){
continue;
}
}
//this will eliminate the duplicated john and ted but only show john 170 and ted 1701.
}
总结一下,我想在每一行中显示所有唯一ID,但不显示重复的用户名。 有没有更好的方法来做到这一点?非常感谢!
答案 0 :(得分:2)
为什么不将这两种方法结合起来?
var endResult = "",
ids = [],
userName;
for (var i = 0, lt = results.length; i < lt; i++)
{
ids.push(results[i].ID);
userName = (i === 0 || results[i].Username != results[i-1].Username) ? results[i].Username : false;
if (userName)
{
endResult += "<div>" + userName + "</div>";
endresult += "<div>" + ids.join("<br>") + "</div>"
//Reset the list of ids
ids = [];
}
}