如何对两个嵌套对象进行排序? [英] How to sort two nested objects?
本文介绍了如何对两个嵌套对象进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
排序此嵌套对象时遇到问题;我拥有的对象是:
I have a problem sorting this nested objects; the object I have is:
Array of objects: [Object, Object]
在此数组内有两个对象,这些对象内有1个对象:2016-5:Object 2016-6:Object
inside this array there are two objects and inside those objects are 1 object: 2016-5:Object 2016-6:Object
在两个对象中的每个内部都是只有1个数字的数组:
Inside every of the two objects are arrays with only 1 number inside:
shift0:Array[1]
shift1:Array[1]
shift2:Array[1]
shift3:Array[1]
并且在数组内部只有一个这样的数字(所有数组的索引均为0):
and inside the array is only one number like so (all with index 0 of the array):
shift0:Array[1] -> 26
shift1:Array[1] -> 42
shift2:Array[1] -> 53
shift3:Array[1] -> 31
我希望能够对数字进行排序-26、42、53、31
I want to be able to sort the numbers - 26, 42, 53, 31
看起来像
var source = [{'2016-5': [{shift0: [26]},
{shift1: [42]},
{shift2: [53]},
{shift3: [31]}]},
{'2016-6': [{shift0: [33]},
{shift1: [15]},
{shift2: [13]},
{shift3: [66]}]}
];
我想要的结果应该是:
var source = [{'2016-5': [{shift0: [26]},
{shift3: [31]},
{shift1: [42]},
{shift2: [53]}]},
{'2016-6': [{shift2: [13]},
{shift1: [15]},
{shift0: [33]},
{shift3: [66]}]}
];
推荐答案
尝试一下
var source = [{'2016-5': [{shift0: [26]},
{shift1: [42]},
{shift2: [53]},
{shift3: [31]}]},
{'2016-6': [{shift0: [33]},
{shift1: [15]},
{shift2: [13]},
{shift3: [66]}]}
];
source.forEach( function(obj){
Object.keys(obj).forEach( function(key){
console.log(obj[key]);
obj[key].sort( function(a,b){
return a[ Object.keys(a)[0] ] - b[ Object.keys(b)[0] ] ;
})
});
});
document.body.innerHTML += JSON.stringify(source, 0, 4 );
这篇关于如何对两个嵌套对象进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文