gpt4 book ai didi

javascript - 数据未排序时如何对数组中的json数据进行排序?

转载 作者:行者123 更新时间:2023-11-28 03:07:26 24 4
gpt4 key购买 nike

var data = [
{
cid: "59eb15be",
parentCid: "",
lv: 1,
number: "2",
subject: "Title 2"
},
{
cid: "d7d851ef",
parentCid: "",
lv: 1,
number: "4",
subject: "Title4"
},
{
cid: "bd01cc50",
parentCid: "ae35e67d",
lv: 2,
number: "1.1",
subject: "Title1.1"
},
{
cid: "2d8bd8b0",
parentCid: "",
lv: 1,
number: "3",
subject: "Title3"
},
{
cid: "7f66a92d",
parentCid: "ae35e67d",
lv: 2,
number: "1.2",
subject: "Title1.2"
},
{
cid: "ae35e67d",
parentCid: "",
lv: 1,
number: "1",
subject: "Title1"
},
{
cid: "e7c2dbcc",
parentCid: "ae35e67d",
lv: 2,
number: "1.3",
subject: "Title1.3"
},
{
cid: "cc784c42",
parentCid: "ae35e67d",
lv: 2,
number: "1.4",
subject: "Title1.4"
}
];
var chapterListDiv = document.getElementById("listSummary");
var store = document.createDocumentFragment(); //we use this to store temporary orphaned childs
for(var i=0; i<data.length; i++){
var node = document.createElement("div");
node.className = "lv" + (data[i].level || data[i].lv);
var content = document.createTextNode(data[i].number + "." + " " + data[i].subject);
node.appendChild(content);
node.setAttribute("data-id", data[i].cid); //set a data-id attribute. We need it for the orphaned values.
node.setAttribute("data-parent-id", data[i].parentCid); //set a data-parent-id attribute. We need it for the orphaned values.
if (data[i].parentCid == "") //we have a root node
{
chapterListDiv.appendChild(node);
}
else
{
var parent = chapterListDiv.querySelector('div[data-id="'+data[i].parentCid+'"]'); //look for a node with the parent id.
if (parent) //parent is found
{
parent.appendChild(node);
}
else
{
store.appendChild(node); //temp store the node.
}
}
}
//final check
var storeChilds = store.querySelectorAll('div[data-parent-id]');
if (storeChilds)
{
Array.prototype.map.call(storeChilds, function(element){
var parent = document.querySelector('div[data-id="'+element.getAttribute("data-parent-id")+'"]') ||
store.querySelector('div[data-id="'+element.getAttribute("data-parent-id")+'"]')
parent.appendChild(element);

});
}
.lv1 {

}

.lv2{
padding-left: 30px;
}

.lv3{
padding-left: 30px;
}
<div id="listSummary"></div>

在 json 数据中,所有元素都有一个“cid”,其中一些元素有“parentCid”,这意味着它是它的子级别。)

作为二级结果

1.3. Title1.3
1.4. Title1.4
1.1. Title1.1
1.2. Title1.2

这不是顺序,因为“1.1”和“1.2”循环访问时找不到父节点,因为它们的父节点在它们后面。这就是为什么“1.3”和“1.4”先附加(父节点在前)的原因。

有什么方法可以像下面的二级一样正确地得到结果吗?

1.1. Title1.1
1.2. Title1.2
1.3. Title1.3
1.4. Title1.4

最佳答案

在处理之前先对数据进行排序

data.sort(function(a, b) {
if ((a.lv | a.level) > (b.lv | b.level))
return 1;
else if ((a.lv | a.level) < (b.lv | b.level))
return -1;
else {
if (Number(a.number) > Number(b.number))
return 1;
else
return -1;
}
});

| a.level 是因为您的数据点之一具有 level 而不是 lv

关于javascript - 数据未排序时如何对数组中的json数据进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31936405/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com