Underscore.js 过滤掉唯一值
Underscore.js to filter out the unique values
这是我的 Fiddle link
我有一个 table 是根据从 Ajax 响应中获得的 JSON 动态创建的。
我在 table 中有重复的条目。例如 xxx,xxx
。
我想将它们分组并使其像 <td data-count="some count">xxx</td>
我尝试使用 underscore.js
,但它似乎破坏了 rowspan
功能。
我使用_countBy(arr)
将arr
转换为一个对象,并获得了以下格式的对象。
{xxx: 2, zzz: 1}
问题 : 如何修改 generateTable()
函数以适应这种变化。我尝试通过以下方式修改它
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>');
}
});
但是行跨度现在似乎是个问题。我该如何修改?
您需要创建这样的函数来转换数据并将其分组:
_.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();
这会将您的数据集转换成这种格式:
{
"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"
]
}
}
]
}
然后您将需要更改制作 table 和计算 rowspan 的业务逻辑。
工作代码here
这是我的 Fiddle link
我有一个 table 是根据从 Ajax 响应中获得的 JSON 动态创建的。
我在 table 中有重复的条目。例如 xxx,xxx
。
我想将它们分组并使其像 <td data-count="some count">xxx</td>
我尝试使用 underscore.js
,但它似乎破坏了 rowspan
功能。
我使用_countBy(arr)
将arr
转换为一个对象,并获得了以下格式的对象。
{xxx: 2, zzz: 1}
问题 : 如何修改 generateTable()
函数以适应这种变化。我尝试通过以下方式修改它
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>');
}
});
但是行跨度现在似乎是个问题。我该如何修改?
您需要创建这样的函数来转换数据并将其分组:
_.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();
这会将您的数据集转换成这种格式:
{
"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"
]
}
}
]
}
然后您将需要更改制作 table 和计算 rowspan 的业务逻辑。
工作代码here