javascript - 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
解决方案
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]));
推荐阅读
- recursion - 这两个定义是相同的还是不同的
- javascript - 使用 CDN 与 NPM/Yarn 进行依赖的优缺点是什么?
- regex - 如何在 PostgreSQL 中提取数字后跟特定字符串?
- firebase - firebase auth 需要关于 twitter 的什么样的许可?(读,读,写,...)
- sql - 在缺少记录的 SQLite 中进行透视
- javascript - Typescript - 手动刷新文本区域
- html - 如何实现在同一行上拥有三个 33.333% 宽度的 DIV 元素,同时在第一个和第二个上拥有 10px 的边距?
- c++ - 根据平台目标修改 OriginalFilename 字符串
- header - 制作和 HttpPOST 操作时出现 Microsoft 刷新卡问题
- unit-testing - 安装 go lang 后无法运行 go test 程序