我想按字母顺序对单个对象进行排序......
保持其关键和价值ex:
输入是: {2:" a",3:" e",4:" h",5:& #34; g",6:" d",7:"我",8:" c",9:" f&#34 ;,10:" b"}
我需要输出: {2:" a",10:" b",8:" c",6: " d",3:" e",9:" f",5:" g",4:" h&# 34;,7:"我"}
这是我的js代码:
var myObject = {2: "a", 3: "e", 4: "h", 5: "g", 6: "d", 7: "i", 8: "c", 9: "f", 10: "b"}
keysSorted = Object.keys(myObject).sort(function(a,b){return myObject[a]-myObject[b]});
console.log(keysSorted);
这是我的小提琴: https://jsfiddle.net/j7yujL2y/
答案 0 :(得分:6)
如果您只想对属性名称数组进行排序,请使用String#localeCompare
来比较字符串。
var myObject = {
2: "a",
3: "e",
4: "h",
5: "g",
6: "d",
7: "i",
8: "c",
9: "f",
10: "b"
}
keysSorted = Object.keys(myObject).sort(function(a, b) {
return myObject[a].localeCompare(myObject[b])
});
console.log(keysSorted);
答案 1 :(得分:0)
奇怪的要求。
你的意思是你需要console.log()的输出看起来像你写的那样? (我认为这是不可能的。:D)
为了完成这项特定的工作,尝试使用alpha作为键创建一个新地图,将数字作为值,尽管它看起来不像你想要的那样
答案 2 :(得分:0)
对象是无序地图,因此您无法对其进行排序 但是,您可以单独获取已排序的键和值 它将是这样的:
let myObject = {2: "Australia", 3: "China", 4: "Japan", 5: "Thailand", 6: "India", 7: "Malaysia", 8: "South Korea", 9: "Hong Kong", 10: "Taiwan", 11: "Philippines", 12: "Vietnam", 13: "France", 14: "United Kingdom", 15: "Germany", 16: "Sweden", 17: "Italy", 18: "Greece", 19: "Spain", 20: "Austria", 21: "The Netherlands", 22: "Belgium", 23: "Switzerland", 24: "United Arab Emirates", 26: "Ukraine", 27: "Russian Federation", 29: "Portugal", 30: "Saudi Arabia", 31: "Denmark", 33: "Norway", 34: "United States", 35: "Canada", 36: "Mexico", 38: "Poland", 39: "Czech Republic", 40: "Ireland", 41: "Bulgaria", 42: "Finland", 43: "Slovenia", 44: "Romania"}
let values = Object.keys(myObject).map(k => myObject[k]).sort();
let keys = Object.keys(myObject)
.sort((a, b) => values.indexOf(myObject[a]) - values.indexOf(myObject[b]));
console.log(values, keys);

答案 3 :(得分:0)
您可以按特定顺序创建Array
或Map
个对象
var myObject = {
2: "a",
3: "e",
4: "h",
5: "g",
6: "d",
7: "i",
8: "c",
9: "f",
10: "b"
};
const keys = Array.from({
length: Object.keys(myObject).length
});
let order = "abcdefghijklmnopqrstuvwxyz";
let arr = [];
const map = new Map();
for (let key in myObject) {
arr[order.indexOf(myObject[key])] = {
[key]: myObject[key]
};
}
for (let prop of arr) {
map.set(prop[Object.keys(prop)], prop)
}
for (let prop of map) {
console.log(prop)
}
console.log(arr);
答案 4 :(得分:0)
你可以尝试这个:
var keysSorted = Object.keys(myObject).sort(function (a, b) {
return myObject[a].localeCompare(myObject[b])
});
var SortedList = [];
keysSorted.forEach(function (value) {
SortedList.push(myObject[value]);
});
答案 5 :(得分:0)
const myObject = {
2: "a",
3: "e",
4: "h",
5: "g",
6: "d",
7: "i",
8: "c",
9: "f",
10: "b"
}
const keysSorted = Object.keys(myObject).sort(function(a, b) {
return myObject[a].localeCompare(myObject[b])
});
console.log(keysSorted);
const sortedObj={};
keysSorted.forEach(key)={
//convert key to string because in JS,Object which has keys as number type are automatically sorted in ascending//
sortedObj[' '+key] = myObject[key];
})
console.log(sortedObj);