如何从dataTables获取不同的值。从下图可以看出
您会看到“课程1”具有相同的值。我希望从“课程名称”中获取所有不同的值,同时使用JS在DataTables中添加相同的不同值的所有等效“学生”。
我希望返回
“课程1,4学生”
已编辑:
HTML CODE:
<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 CODE:
"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"
}
],
答案 0 :(得分:1)
要计算分配到每个课程的人员,您可以使用数组的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)
&#13;
答案 1 :(得分:1)
来自@ 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
}, []);
}
使用JSFiddle here。