Sort JSON response by key value

后端 未结 3 2128
半阙折子戏
半阙折子戏 2021-01-20 16:57

Before you tag this as duplicate - I\'ve gone through these answers:

Sort JSON by array key value

Sort a JSON array object using Javascript by value

3条回答
  •  孤城傲影
    2021-01-20 17:33

    Your response seems to be an object, which can't be sorted. You first want to convert it into an array

    const res = //... your response
    const array = Object.keys(res).map(key => res[key]);
    

    Now you can use the Array.sort function to sort your items by their index:

    array.sort((itemA, itemB) =>  itemA - itemB)
    

    Be aware that the sort function directly mutates the array.

    See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

提交回复
热议问题