簡體   English   中英

按鍵按字母順序對 Object.entries 進行排序

[英]Sort Object.entries alphabetically by key

說我有這個:

for(let [k,v] of Object.entries({a:1,b:2}).sort((a,b) => b[0] - a[0])){
  console.log({k,v});
}

我總是得到這個輸出:

{ k: 'a', v: 1 }
{ k: 'b', v: 2 }

即使我將其切換為:

a[0] - b[0]

為什么我不能按字母順序對鍵進行排序?

比較字符串時,使用localeCompare()幾乎總是更好。 它為您提供了更多的靈活性和選項來處理大寫、國際字符和數字。 它返回的正是sort()想要的:

 let arr = Object.entries({a:1,b:2}) arr.sort((a,b) => b[0].localeCompare(a[0])) console.log(arr) arr.sort((a,b) => a[0].localeCompare(b[0])) console.log(arr)

nvm,我的問題沒有意義,字符串的減法沒有明顯的定義。 這雖然有效。

const sorter = (a,b) => b[0] > a[0] ? 1 :  (b[0] < a[0] ? -1 : 0);

const sorted = Object.entries({a:1,b:2}).sort(sorter);

for(let [k,v] of sorted){
  console.log({k,v});
}

如果您想按字母順序排序,我建議使用String.localeCompare()

 let sortAsc = Object.entries({a:1, b:2}).sort((a, b) => a[0].localeCompare(b[0])); let sortDesc = Object.entries({a:1, b:2}).sort((a,b) => b[0].localeCompare(a[0])); console.log("Ascending:"); for(let [key, val] of sortAsc) { console.log(key, val); } console.log("Descending:"); for(let [key, val] of sortDesc) { console.log(key, val); }
 .as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;}

實現此目的的另一個技巧是使用fromEntries從排序的鍵構造一個新對象:

 const data = { b: 2, c: 3, a: 1 } const sortedData = Object.fromEntries( Object.keys(data).sort().map(key => [key, data[key]]) ) console.log({ data, sortedData })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM