【发布时间】:2020-06-19 21:09:14
【问题描述】:
我有一个对象数组,其中包含许多级别的嵌套子项,我需要通过比较同一级别项的两个属性来对其进行排序。数组有多个嵌套项,所以我带来了这个需要排序的最小数组。
每个项目至少有 3 个属性(路径、标题和上一个),并且一些项目可能具有与子项目相似的项目。
// unsorted array
const original = [
{
"path": "path3",
"title": "title3",
"previous": "title2",
"children": [
{ "path": "child31", "title": "child31", "previous": null },
{ "path": "child32", "title": "child32", "previous": "child31" },
{ "path": "child33", "title": "child33", "previous": "child32" }
]
},
{
"path": "path1",
"title": "title1",
"previous": null,
"children": [
{ "path": "child11", "title": "child11", "previous": null },
{ "path": "child13", "title": "child13", "previous": "child12" },
{ "path": "child14", "title": "child14", "previous": "child13" },
{ "path": "child12", "title": "child12", "previous": "child11",
"children": [
{ "path": "child123", "title": "child123", "previous": "child122" },
{ "path": "child121", "title": "child121", "previous": null },
{ "path": "child122", "title": "child122", "previous": "child121",
"children": [
{ "path": "child1221", "title": "child1221", "previous": null,
"children": [
{
"path": "child12211",
"title": "child12211",
"previous": null
},
{
"path": "child1222",
"title": "child1222",
"previous": "child1221"
}
]
},
{
"path": "child1224",
"title": "child1224",
"previous": "child1223"
},
{
"path": "child1222",
"title": "child1222",
"previous": "child1221"
},
{
"path": "child1223",
"title": "child1223",
"previous": "child1222",
"children": [
{
"path": "child12231",
"title": "child12231",
"previous": null
}
]
}
]
}
]}
]
},
{ "path": "path2", "title": "title2", "previous": "title1" }
];
我需要通过比较同一父项中项目的先前值和标题值来对该数组进行排序。如果 previous 为 null 任何项目,那将是该父项中的第一个项目,对于下一个项目,previous 将是它的前一个兄弟的标题,依此类推。
这是我的排序功能:
const sortNav = items => {
let result = [...items].sort(function (a, b) {
if(a.title === b.previous || a.previous === null) {
return -1;
}
if (a.previous === b.title || b.previous === null) {
return 1;
}
return 0;
})
for(let i = 0; i < items.length; i++) {
if (items[i].children && items[i].children.length) {
items[i].children = sortNav(items[i].children);
}
}
return result;
};
我正在使用这样的功能
const sorted = sortNav(original);
【问题讨论】:
-
您应该在问题中包含您的初始数据以及您想要的结果
-
@Gershom 初始数据在 pastebin,我没有预期的数据,将用这个更新问题
-
您发现哪些条目在排序时优先级错误?
-
@MadanBhandari 如果您能提供一个更小的初始数据集及其预期结果可能会有所帮助,以便我们更简洁地了解您想要什么
-
@Tibebes.M 内部(第 3 个或更多)子级排序错误
标签: javascript node.js