[英]Sorting an array of objects by object key
如何通過檢查對象的鍵對這個對象數組進行排序?
const list = [
{ "firstValue": { "a": "1" } },
{ "secondValue": { "b": "1" } },
{ "thirdValue": { "c": "1" } },
{ "fourthValue": { "d": "1" } },
{ "fifthValue": { "e": "1" } }
]
所以在這種情況下,我希望它被排序為:
const list = [
{ "fifthValue": { "e": "1" } },
{ "firstValue": { "a": "1" } },
{ "fourthValue": { "d": "1" } },
{ "secondValue": { "b": "1" } },
{ "thirdValue": { "c": "1" } }
]
這是我當前的代碼:
sortArrOfObjectsByKey(list);
document.write(JSON.stringify(list))
function sortArrOfObjectsByKey(arrToSort) {
arrToSort.sort(function(a, b) {
return a < b ? -1 : 1
});
}
但它沒有正確排序。 請注意,新的排序數組/對象不應該有任何新容器。 幫助! 謝謝
您需要獲取屬性名稱,然后根據該名稱進行排序
const list = [ { "firstValue": { "a": "1" } }, { "secondValue": { "b": "1" } }, { "thirdValue": { "c": "1" } }, { "fourthValue": { "d": "1" } }, { "fifthValue": { "e": "1" } } ] list.sort( function(a, b) { const aKey = Object.keys(a)[0]; const bKey = Object.keys(b)[0]; return aKey.localeCompare(bKey) } ); console.log(list)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.