我正在尝试显示从我的数据库返回的记录
我返回的数据如下:
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,但不显示重复的用户名。 有更好的方法吗?非常感谢!
最佳答案
为什么不结合这两种方法呢?
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 = [];
}
}
关于javascript - 如何避免在不同行中显示重复的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13848168/