Underscore.js to filter out the unique values

2019-05-07 16:12发布

Here is a link to my Fiddle

I have a table that is created dynamically from the JSON obtained from a Ajax response.

I have duplicate entries in the table. For example xxx,xxx. I want to group them and have it like <td data-count="some count">xxx</td>

I tried using underscore.js but it seems to break the rowspan functionality.

I converted the arr into a object using _countBy(arr) and I obtained an object of the following format.

{xxx: 2, zzz: 1}

Question : How can I modify the generateTable() function to accommodate this change. I tried to modify it the following way

var i=0;

$.each(queryObject,function(key,value){
   if(i == 0){
       i++;
       childrenHtml += ('<td rowspan="1" data-count="'+value+'">' + key + '</td>' + '</tr>');
   }
   else{
    childrenHtml += ('<tr><td rowspan="1" data-count="'+value+'">' + key + '</td>' + '</tr>');
   }
});

But the rowspan seems to be problem now. How can I modify this?

1条回答
ゆ 、 Hurt°
2楼-- · 2019-05-07 16:15

You will need to make function like this to convert your data and group it:

  _.chain(data.result)
    .keys()//get all the keys buildname1 buildname2..etc
    .flatten()
    .each(function(key) {//for each key do a mapping and return a grouping.
      data.result[key] = _.chain(data.result[key]).flatten().map(function(d) {
        var key = _.chain(d).keys().first().value();
        var ob = {};
        ob[key] = _.chain(d).values().flatten().groupBy().value();//grouping by value
        return ob;
      }).value();
    }).value();

This will convert your data set into this format:

{
   "buildname1":[
      {
         "table1":{
            "xxx":[
               "xxx"
            ],
            "zzz":[
               "zzz",
               "zzz"
            ]
         }
      },
      {
         "table2":{
            "xxx":[
               "xxx"
            ],
            "yyy":[
               "yyy"
            ]
         }
      }
   ],
   "buildname2":[
      {
         "table1":{
            "xxx":[
               "xxx",
               "xxx"
            ],
            "zzz":[
               "zzz"
            ]
         }
      },
      {
         "table2":{
            "xxx":[
               "xxx",
               "xxx"
            ]
         }
      },
      {
         "table3":{
            "xxx":[
               "xxx"
            ],
            "yyy":[
               "yyy"
            ]
         }
      }
   ]
}

Then you will need to change the biz logic for making table, and calculating rowspan.

working code here

查看更多
登录 后发表回答