[英]How can I sort an object alphabetically by value?
So I have a list of countries, by default they come sort by ISOA2 Code which is some kind of country code.所以我有一个国家列表,默认情况下它们按 ISOA2 代码排序,这是某种国家代码。
Say this list:说出这个清单:
{
"AD": "Andorra",
"AE": "United Arab Emirates",
"AF": "Afghanistan",
"AG": "Antigua and Barbuda",
"AI": "Anguilla",
"AL": "Albania",
"AM": "Armenia",
"AN": "Netherlands Antilles",
"GB": "United Kingdom"
}
And I have this code:我有这个代码:
function sortObject(obj) {
return Object
.keys(obj)
.sort()
.reduce((a, v) => {
a[v] = obj[v];
return a;
}, {});
}
// data is the list of countries
const result = sortObject(data);
I am trying to sort it with that code but it always returns the same list.我正在尝试使用该代码对其进行排序,但它始终返回相同的列表。
I need the list to be like this:我需要这个列表是这样的:
{
"AF": "Afghanistan",
"AL": "Albania",
"AD": "Andorra",
"AI": "Anguilla",
"AG": "Antigua and Barbuda",
"AM": "Armenia",
"AN": "Netherlands Antilles",
"AE": "United Arab Emirates",
"GB": "United Kingdom"
}
What am I doing wrong?我究竟做错了什么?
You can play around here:你可以在这里玩:
https://codesandbox.io/s/js-playground-forked-xk005?file=/src/index.js https://codesandbox.io/s/js-playground-forked-xk005?file=/src/index.js
You will see the result in the console.您将在控制台中看到结果。
Take the Object.entries
sort them by value, then use Object.fromEntries
to turn this array of key-value pairs back into an object:将Object.entries
按值排序,然后使用Object.fromEntries
将此键值对数组转换回 object:
Object.fromEntries(
Object.entries(obj)
.sort(([keyA, valueA], [keyB, valueB]) => valueA.localeCompare(valueB))
)
Note that sorting objects is senseless if there are numeric keys or if the object is mutated (as that changes sort order again).请注意,如果有数字键或 object 发生突变(因为这会再次更改排序顺序),则排序对象是没有意义的。
Try this for sorting:试试这个进行排序:
const sortObject = obj => {
const ret = {}
Object.values(obj)
.sort()
.forEach(val => {
const key = Object.keys(obj).find(key => obj[key] === val)
ret[key] = val
})
return ret
}
Does this works for you?这对你有用吗?
function sortObject(obj) { return Object.fromEntries(Object.entries(obj).sort((a,b)=>a[1].localeCompare(b[1]))); } const data = { "AD": "Andorra", "AE": "United Arab Emirates", "AF": "Afghanistan", "AG": "Antigua and Barbuda", "AI": "Anguilla", "AL": "Albania", "AM": "Armenia", "AN": "Netherlands Antilles", "GB": "United Kingdom" } // data is the list of countries const result = sortObject(data); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.