0

我正在尝试显示从我的数据库返回的记录

我返回的数据如下:

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,但不显示重复的用户名。有没有更好的方法来做到这一点?非常感谢!

4

1 回答 1

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 = [];
    }
}
于 2012-12-12T20:51:09.950 回答