简体   繁体   中英

Underscore.js to filter out the unique values

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM