我已经创建了一个AJAX网站,我在多维json数组中获得响应,我相处得很好,但我对某些元素的排序有问题,我发现订单无法保证对象,所以我试图将其转换为数组,以在Jquery中排序下面的json样本
"lib":{"239":{"stitle":"Agents of S.H.I.E.L.D.","title":"Agents of S.H.I.E.L.D.","img":"image2.jpg"},"203":{"stitle":"Alexei Sayle's Stuff","title":"Alexei Sayle's Stuff","img":"image2.jpg"},"92":{"stitle":"Anatomy for Beginners","title":"Anatomy for Beginners","img":"image3.jpg"},"180":{"stitle":"Angry Birds","title":"Angry Birds","img":"image4.jpg"}}}
我试图将对象转换为数组,但似乎只是把对象放在一个数组中,所以仍然有一个排序数组的问题,下面是我的工作,但似乎是按索引排序而不是按顺序排序来自json。
$.each(data.lib, function(index, value){
$('.medlst').append('<li class="sersel" id="'lnk_'+index+'"><img src="'+ value.img +'" alt="'+ value.stitle +'" title="'+ value.title +'" height="130px" width="90"></li>');
});
我试图使用$ .parseJSON()但这会将json转换为我已经拥有的对象
如果有人知道如何将对象和所有子对象转换为嵌套数组,该数组将遵循接收json的顺序,我将不胜感激
答案 0 :(得分:0)
提供的JSON字符串无效,因此只需稍加修改版本,您可以执行以下操作。
const str = '{"lib":{"239":{"stitle":"Agents of S.H.I.E.L.D.","title":"Agents of S.H.I.E.L.D.","img":"image2.jpg"},"203":{"stitle":"Alexei Sayle\'s Stuff","title":"Alexei Sayle\'s Stuff","img":"image2.jpg"},"92":{"stitle":"Anatomy for Beginners","title":"Anatomy for Beginners","img":"image3.jpg"},"180":{"stitle":"Angry Birds","title":"Angry Birds","img":"image4.jpg"}}}';
let libs = JSON.parse(str);
// Create an array and populate with
// libs object from JSON, adding
// key into each
var sortedLibs = [];
for(let key in libs.lib) {
libs.lib[key].key = parseInt(key);
sortedLibs.push(libs.lib[key]);
}
// Sort libs based on key, ascending
sortedLibs.sort((a, b) => a.key > b.key);
console.log(sortedLibs);
// Sort libs based on key, descending
sortedLibs.sort((a, b) => a.key < b.key);
console.log(sortedLibs);
&#13;