如何从dataTables获取不同的值。你可以从下面的图片中看到
您将看到“Course 1”具有相同的值。我希望从“课程名称”中获得所有不同的值,同时使用JS在DataTables中从相同的不同值中添加所有等效的“学生”。
我想要的回报是
课程1,4名学生
编辑:
HTML代码:
<table class="table" id="bookingReport" cellspacing="0" width="100%">
<thead class="thead-inverse">
<tr>
<th><h4>Course Names</h4></th>
<th><h4>Names</h4></th>
<th><h4>Dates</h4></th>
</tr>
</thead>
</table>
JS代码:
"dataSrc": function(result) {
var obj, id, paymentMethod;
var validatedResult = [];
$.each(result.aaData, function(index, value) {
var givenName, surname, organisationName;
id = value.id;
dateCreated = value.dateCreated;
$.each(value.bookingDetail, function(i, v) {
$.each(v.student.studentCourseDetail, function(ii, sd) {
obj = new Object();
obj["id"] = sd.id;
obj["surname"] = surname;
obj["givenName"] = givenName;
obj["dateCreated"] = dateCreated;
obj["courseName"] = sd.courseName;
validatedResult.push(obj);
});
});
});
return validatedResult;
}, },
"aoColumns": [{
"data": "courseName"
}, {
"data": "givenName"
}, {
"data": "dateCreated"
}
],
发布于 2017-03-07 15:34:12
要统计分配给每个课程的人数,可以使用数组的reduce
函数。给出下面的学生数组,你可以很容易地计算出结果。
var bookingList = [{
id: 1,
name: 'Alice',
courseName: 'Physics'
},
{
id: 2,
name: 'Bob',
courseName: 'Physics'
},
{
id: 3,
name: 'Emily',
courseName: 'Math'
},
{
id: 1,
name: 'Alice',
courseName: 'Math'
},
{
id: 4,
name: 'Jane',
courseName: 'Biology'
},
{
id: 5,
name: 'Dan',
courseName: 'Chemistry'
}
]
var result = bookingList.reduce(function(prevValue, currValue, index, array) {
var bookingEntry = array[index]
if (prevValue[bookingEntry.courseName] == null) {
prevValue[bookingEntry.courseName] = 1
} else {
prevValue[bookingEntry.courseName]++
}
return prevValue
}, {});
console.log(result)
发布于 2017-03-07 15:51:26
来自@t3mplar的很好的答案,这是一个使用模拟ajax的版本,它还考虑了相同课程在不同日期发生的可能性:
"dataSrc": function(data) {
return data.reduce(function(returnedArray, currentElement, index, originalArray) {
let foundOne = returnedArray.findIndex(function(element) {
return currentElement.course === element.course && currentElement.date === element.date
});
if (foundOne < 0) {
returnedArray.push({
"course": currentElement.course,
"date": currentElement.date,
"students": 1
});
} else {
returnedArray[foundOne].students++;
}
return returnedArray
}, []);
}
Working JSFiddle here。
https://stackoverflow.com/questions/42641771
复制相似问题