如何在javascript中对嵌套对象数组进行排序 [英] How To sort an array of nested objects in javascript
本文介绍了如何在javascript中对嵌套对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的数组
var array = [{
order: 3,
sub - array: [{
order: 2
},{
order: 1
}]
},{
order: 2,
sub - array: [{
order: 2
},{
order: 1
}]
}];
现在我想对属性 order
上的完整集合进行排序,所以外部
以及内部数组都应该根据属性顺序进行排序。
Now I want to sort the the complete collection on the attribute order
, so both the outer
as well as inner arrays should get sorted based on the attribute order.
最终输出应该如下所示。
The final output should look like this.
var array = [{
order: 2,
sub - array: [{
order: 1
},{
order: 2
}]
},{
order: 3,
sub - array: [{
order: 1
},{
order: 2
}]
}];
推荐答案
var propertySort = function(a, b){
return a.order > b.order ? 1 : (a.order < b.order ? -1 : 0);
}
var reorder = function(arr){
var l = arr.length;
while (l--){
if (arr[l]['sub-array']){
reorder(arr[l]['sub-array']);
}
}
arr.sort(propertySort);
};
reorder(arr);
console.log(arr);
这应该为任意数量的嵌套级别重新排序数组。
This should re-order the array for any number of nested levels.
这篇关于如何在javascript中对嵌套对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文