[英]Sort javascript object key into array based on object's value
Let say I have an object with numbers as key and string as value 假设我有一个对象,数字为键,字符串为值
var obj = {
'24': 'Sean',
'17': 'Mary',
'88': 'Andrew',
'46': 'Kelvin'
}
Is there an easy way to sort the keys into an array based on their value where the result will looks like this: 是否有一种简单的方法可以根据键的值将键排序到数组中,其结果如下所示:
[88,46,17,24]
Here's one way to do it: 这是一种方法:
var obj = { '24': 'Sean', '17': 'Mary', '88': 'Andrew', '46': 'Kelvin' } var sortedKeys = Object.keys(obj).sort(function(a, b) { return obj[a].localeCompare(obj[b]); }).map(Number) console.log(sortedKeys)
Omit the .map()
part if you are happy for the result to be an array of strings rather than numbers. 如果您对结果是字符串数组而不是数字感到满意,请省略
.map()
部分。
Further reading: 进一步阅读:
Or the same thing but with ES6 arrow functions : 或者同样的事情,但使用ES6箭头功能 :
const sortedKeys = Object.keys(obj)
.sort((a, b) => obj[a].localeCompare(obj[b]))
.map(Number)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.