Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a problem sorting this nested objects; the object I have is:

Array of objects: [Object, Object]

inside this array there are two objects and inside those objects are 1 object: 2016-5:Object 2016-6:Object

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]

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

I want to be able to sort the numbers - 26, 42, 53, 31

so it looks like

var source = [{'2016-5': [{shift0: [26]}, 
                       {shift1: [42]}, 
                       {shift2: [53]}, 
                       {shift3: [31]}]},
           {'2016-6':  [{shift0: [33]}, 
                        {shift1: [15]}, 
                        {shift2: [13]}, 
                        {shift3: [66]}]}
 ];

the result i want should be:

var source = [{'2016-5': [{shift0: [26]}, 
                           {shift3: [31]}, 
                           {shift1: [42]}, 
                           {shift2: [53]}]},
               {'2016-6':  [{shift2: [13]}, 
                            {shift1: [15]}, 
                            {shift0: [33]}, 
                            {shift3: [66]}]}
     ];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
182 views
Welcome To Ask or Share your Answers For Others

1 Answer

try this

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 );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...