本文介绍了以原始顺序迭代jQuery JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在地图对象中有一些按时间排序的json数据。键是整数id,值是包含时间戳的对象。但是,当我尝试使用jQuery $ .each函数迭代这些数据时,结果将按键排序。如何以原始顺序迭代我的对象集合?
I've got some json data in a map object which is sorted by time. The key is an integer id and the value is an object which contains a timestamp. However when I try to iterate over this data with the jQuery $.each function, the results come back sorted by the key instead. How can I iterate over my collection of objects in their original order?
代码示例:
$.getJSON(url, addPages);
function addPages(pageData) {
$.each(pageData, function(key,value){
alert(key+' : '+value);
}
}
推荐答案
您可以将键值对复制到数组中对象然后使用Array.sort将它们按顺序排列。
You could copy the key value pairs into an array of objects and then use Array.sort to put them in order.
// $.getJSON(url, addPages); //removed for test purposes
function addPages(pageData) {
var pageItems = [];
$.each(pageData, function(key,value){
pageItems.push( { key: key, value: value } );
});
// Assuming you can do arithmetic on timestamps
pageItems.sort( function(a,b){ return a.value.timeStamp - b.value.timeStamp; } );
$.each(pageItems, function(index,pageItem){
alert(pageItem.key+' : '+pageItem.value.timeStamp);
});
}
我的测试脚本:
var testData = {
'12': { timeStamp: 55 },
'16': { timeStamp: 655 },
'123': { timeStamp: 455 },
'312': { timeStamp: 955 },
'132': { timeStamp: 255 },
'126': { timeStamp: 455 },
'162': { timeStamp: 355 }
};
addPages(testData);
这篇关于以原始顺序迭代jQuery JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!