[英]Sorting JavaScript Object by property value (Numeric Key)
等一下 在標記為重復或否決之前
假設我有一個如下的Java腳本對象,我想按值對該對象進行排序,是的,我知道數組是為此發明的,並且具有內置的sort
但是由於某種原因,我必須使用該對象:(
var myObj = {"you": 100, "me": 75,"11111": 20, "foo": 116, "bar": 15};
直到現在我最終
{11111: 20, bar: 15, me: 75, you: 100, foo: 116}
但您可以看到它不是您想要的,因為在這種情況下,我嘗試使用此剝奪的解決方案中的許多解決方案,因為此處的代碼如下
Object
.keys(myObj)
.sort((a, b) => myObj[a]-myObj[b])
.reduce((_sortedObj, key) => ({
..._sortedObj,
[key]: myObj[key]
}), {})
編輯我已經看到了這個問題,這不是我的情況,因為我有數值,因此那里沒有任何單個答案對我有幫助
這不可能。
在ES2015 +中,對象屬性的遍歷順序為:
即使您在末尾添加11111
鍵,也總是在使用Object.keys()
或for...in
循環時首先獲取它
const obj = {}; obj["first"] = 1 obj["second"] = 2 obj["200"] = 200 // integer keys obj["100"] = 100 // 100 and 200 property will be moved to the top even if they are added in the end // 200 was added before 100, but it will be printed after 100 // because integer indices are traversed in ascending numeric order console.log(obj) // 100 will be the first key console.log(Object.keys(obj))
您可以改用Map
對象。 它具有鍵值對,並記住鍵的原始插入順序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.