[英]Sorting an array of objects by object key
How do I sort this array of objects by checking the objects' key?如何通过检查对象的键对这个对象数组进行排序?
const list = [
{ "firstValue": { "a": "1" } },
{ "secondValue": { "b": "1" } },
{ "thirdValue": { "c": "1" } },
{ "fourthValue": { "d": "1" } },
{ "fifthValue": { "e": "1" } }
]
So in this case I want it to be sorted like:所以在这种情况下,我希望它被排序为:
const list = [
{ "fifthValue": { "e": "1" } },
{ "firstValue": { "a": "1" } },
{ "fourthValue": { "d": "1" } },
{ "secondValue": { "b": "1" } },
{ "thirdValue": { "c": "1" } }
]
This is my current code:这是我当前的代码:
sortArrOfObjectsByKey(list);
document.write(JSON.stringify(list))
function sortArrOfObjectsByKey(arrToSort) {
arrToSort.sort(function(a, b) {
return a < b ? -1 : 1
});
}
But it doesn't get sorted correctly.但它没有正确排序。 Please note that there shouldn't be any new container for the new sorted array/object.
请注意,新的排序数组/对象不应该有任何新容器。 Help!
帮助! Thanks
谢谢
You need to fetch property name and then sort according to that您需要获取属性名称,然后根据该名称进行排序
const list = [ { "firstValue": { "a": "1" } }, { "secondValue": { "b": "1" } }, { "thirdValue": { "c": "1" } }, { "fourthValue": { "d": "1" } }, { "fifthValue": { "e": "1" } } ] list.sort( function(a, b) { const aKey = Object.keys(a)[0]; const bKey = Object.keys(b)[0]; return aKey.localeCompare(bKey) } ); console.log(list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.