简体   繁体   中英

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM