用对象的ID排序

时间:2019-04-14 10:20:02

标签: javascript arrays object

嗨,我需要按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}
]

1 个答案:

答案 0 :(得分: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)