【发布时间】:2019-01-02 02:40:23
【问题描述】:
假设我们有一个对象数组,其中每个对象代表一个类别或子类别,如下所示:
var data = [
{type: "parent-category", order: 1, categoryId: 1},
{type: "parent-category", order: 2, categoryId: 2},
{type: "child-category", order: 1, categoryId: 3, parentCategoryId: 1},
{type: "child-category", order: 2, categoryId: 4, parentCategoryId: 1},
{type: "child-category", order: 2, categoryId: 5, parentCategoryId: 2},
{type: "child-category", order: 1, categoryId: 6, parentCategoryId: 2}
];
这个数组表示一个包含两个类别的示例,其中每个类别还有两个子类别。
现在,我面临以某种自定义方式对该数组进行排序的问题。如您所见,每个对象内的order 属性与对象在其层次结构中的位置(或顺序)相关。并且类别和子类别之间的关系由parentCategoryId属性定义。
我需要的预期排序,以前面的数据数组为例,应该是这个:
var data = [
{type: "parent-category", order: 1, categoryId: 1},
{type: "child-category", order: 1, categoryId: 3, parentCategoryId: 1},
{type: "child-category", order: 2, categoryId: 4, parentCategoryId: 1},
{type: "parent-category", order: 2, categoryId: 2},
{type: "child-category", order: 1, categoryId: 6, parentCategoryId: 2},
{type: "child-category", order: 2, categoryId: 5, parentCategoryId: 2}
];
我目前解决此问题的方法是基于创建数字映射,分析具有以下条件的属性值:
- 对于类型为 parent-category 的对象,我们分配
categoryId * 1000的值。 - 对于具有类 child-category 的对象,我们分配
(parentCategoryId * 1000) + order的值
这个逻辑显示在下一个排序实现中:
let data = [
{type: "parent-category", order: 1, categoryId: 1},
{type: "parent-category", order: 2, categoryId: 2},
{type: "child-category", order: 1, categoryId: 3, parentCategoryId: 1},
{type: "child-category", order: 2, categoryId: 4, parentCategoryId: 1},
{type: "child-category", order: 2, categoryId: 5, parentCategoryId: 2},
{type: "child-category", order: 1, categoryId: 6, parentCategoryId: 2}
];
let orderedData = data.sort((a, b) =>
{
var aCat = (a.type == "parent-category") ? a.categoryId : a.parentCategoryId;
var aOrder = (a.type == "parent-category") ? 0 : a.order;
var bCat = (b.type == "parent-category") ? b.categoryId : b.parentCategoryId;
var bOrder = (b.type == "parent-category") ? 0 : b.order;
return (aCat * 1000 + aOrder) - (bCat * 1000 + bOrder);
});
console.log(orderedData);
但是,忽略以前的实现有效的事实,我的问题是是否存在更好的方法或替代方案来解决这个问题。我不喜欢依赖映射到数字的想法,因为例如,以前的实现引入了对子类别数量的限制(在这种情况下为999),我可以在每个类别下正确排序。谢谢!
【问题讨论】:
标签: javascript arrays sorting