首页 > 解决方案 > Sort an array of objects(with multiple properties) in a specified order of Keys with JavaScript

问题描述

I have a json response with the following data in alphabetical order,

let sheetCells =
{
  0: [
     {
      "Actual Hours": 16
      "Assigned": "Jerry"
      "Completion %": 48.2
      "Days Scheduled": 2
      "Device 1": 10
      "Device 2": 43
      "Device 3": 72
      "Device 4": 91
      "Device 5": 25
      "End Date": "2018-01-03T23:00:00.000Z"
      "Estimated Hours": 16
      "ID": "1dbk3"
      "Notes": "Note 1"
      "Parent ID": "2k59f"
      "Priority": ""
      "Start Date": "2018-01-01T23:00:00.000Z"
      "Stories": "A User"
      "Tests": "Y"
     },
     {
      //...same keys as above, different values
     }
   ]
}

but this is the DESIRED format in which I want the resulting objects in the array be sorted,

[ 
  {
   "Stories": "A User" 
   "ID": "1dbk3"
   "Parent ID": "2k59f"  
   "Completion %": 48.2 
   "Priority": "" 
   "Device 1": 10
   "Device 2": 43
   "Device 3": 72
   "Device 4": 91
   "Device 5": 25 
   "Assigned": "Jerry" 
   "Notes": "Note 1"
   "Tests": "Y"
   "Estimated Hours": 16 
   "Days Scheduled": 2 
   "Start Date": "2018-01-01T23:00:00.000Z" 
   "End Date": "2018-01-03T23:00:00.000Z" 
   "Actual Hours": 16
  },
  {
   //...same keys as above, different values
  }
 ]

Here is the solution that i've tried

let sortOrder = ['Stories', 'ID', 'Parent ID', 'Completion %', 'Priority', 'Device 1', 'Device 2', 'Device 3', 'Device 4', 'Device 5', 'Assigned', 'Notes', 'Tests', 'Estimated Hours', 'Days Scheduled', 'Start Date', 'End Date', 'Actual Hours']

let result = sheetCells[0].sort((a,b) => sortOrder.indexOf(a.Stories) > sortOrder.indexOf(b.Stories)))

but this result gets just the story key and ignores the rest, please help with a working and optimal solution.Thanks

标签: javascriptarraysjsonsortingobject

解决方案


Rather than resorting the original data, you can map it to a new sorted array by indexing it with every element in your sortOrder in order. Something like this:

let result = sortOrder.map(key => sheetCells[0][key]);

While that's a working version of your solution, based on the data structure in your example, this may be closer to what you're looking for:

let result = sheetCells[0].map(cell => sortOrder.map(key => cell[key]));

推荐阅读