嗨,我需要通过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}
}
}
输出:
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}
}
}
或者例如将{id: 3, name: "olom", catId: 3}
推送到空数组:
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}
]
你可以像这样使用Object.values
和sort
:
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)