我一直在嘗試從按照字母順序輸入/輸入到HTML文檔的JSON文檔中獲取數據。我發現堆棧溢出的類似請求;但是,在實現當前代碼的解決方案時,JSON數據不會根據需要進行重組。按字母順序排列JSON數據
當前的代碼:
$(document).ready(function() {
//Content Viewer Information
function checkViewers() {
//Base Variables
var viewer = $('#viewed span.user');
var totalViews = $('#viewed span.user').length;
var shortenViews = $('#viewed span.user').length -1;
if (totalViews === 0) {
$('<span> 0 people have </span>').insertBefore($('#viewed span:last-child'));
}
if (totalViews === 2) {
$('<span> and </span>').insertAfter(viewer.first());
}
if (totalViews >= 3) {
viewer.slice(1).hide();
$('<span> and </span>').insertAfter(viewer.first());
$('<span class="user count"></span>').insertAfter(viewer.eq(2));
$('.count').html(shortenViews + ' more people');
}
}
//JSON Data
var xhr = new XMLHttpRequest();
//Sort Alphabetically
function SortAlphabetically(a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
xhr.onload = function() {
if (xhr.status === 200) {
responseObject = JSON.parse(xhr.responseText);
var newViewers = '';
for (var i = 0; i < responseObject.profiles.length; i++) {
newViewers += '<span class="user">' + responseObject.profiles[i].firstName + ' ';
newViewers += responseObject.profiles[i].lastName + '</span>';
newViewers += ' ';
}
responseObject.profiles.sort(function(a, b) {
return SortAlphabetically(a.firstName, b.firstName);
});
console.log('JSON Sorted');
//Update Page With New Content
var viewerSection = $('#viewed');
viewerSection.html(newViewers);
}
};
xhr.open('GET', 'data.json', true);
xhr.send(null);
checkViewers();
});
我不知道該解決方案將是對這一問題的是什麼,或者是否有可能是一個更好的方向與按字母順序排序JSON數據去。任何意見或幫助表示讚賞。
查看當前的代碼和示例Plunker。
您可以張貼了一下JSON對象?像responsObject.profiles數組? –