从对象的id排序

问题描述 投票:-4回答:1

嗨,我需要通过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}
]
javascript arrays object
1个回答
3
投票

你可以像这样使用Object.valuessort

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)
© www.soinside.com 2019 - 2024. All rights reserved.