首页 > 解决方案 > sort with id from object

问题描述

hi i need sort this object by catId :

book {
books : {
1: {id: 1, name: "javascript", catId: 2}
2: {id: 2, name: "ayat", catId: 1}
3: {id: 3, name: "olom", catId: 3}
4: {id: 4, name: "css", catId: 2}
5: {id: 5, name: "chap", catId: 1}
}
}

output :

book {
books : {
2: {id: 2, name: "ayat", catId: 1}
5: {id: 5, name: "chap", catId: 1}
4: {id: 4, name: "css", catId: 2}
1: {id: 1, name: "javascript", catId: 2}
3: {id: 3, name: "olom", catId: 3}
}
}

or for example push {id: 3, name: "olom", catId: 3} to a empty array :

arrBooks [
{id: 2, name: "ayat", catId: 1}
{id: 5, name: "chap", catId: 1}
{id: 4, name: "css", catId: 2}
{id: 1, name: "javascript", catId: 2}
{id: 3, name: "olom", catId: 3}
]

标签: javascriptarraysobject

解决方案


You can use Object.values and sort like this:

const book = {
books : {
   1: {id: 1, name: "javascript", catId: 2},
   2: {id: 2, name: "ayat", catId: 1},
   3: {id: 3, name: "olom", catId: 3},
   4: {id: 4, name: "css", catId: 2},
   5: {id: 5, name: "chap", catId: 1}
 }
}

const sortedBooks = Object.values(book.books)
                          .sort((a, b) => a.catId - b.catId)
                          
console.log(sortedBooks)


推荐阅读