[英]Sort object keys by custom logic
I have an object in javascript that looks like this:我在 javascript 中有一个 object,如下所示:
const inventory = {
fall: { 'Category 1': [], 'Category 2': [] },
spring: { 'Category 1': [], 'Category 3': [] },
winter: { 'Category 3': [], 'Category 4': [] },
summer: { 'Category 4': [], 'Category 5': [] }
}
How can I sort by keys so that those are ordered as follows:如何按键排序,以便按如下方式排序:
Destructuring assignment解构赋值
const { spring, summer, fall, winter } = {
fall: { 'Category 1': [], 'Category 2': [] },
spring: { 'Category 1': [], 'Category 3': [] },
winter: { 'Category 3': [], 'Category 4': [] },
summer: { 'Category 4': [], 'Category 5': [] }
};
const inventory = { spring, summer, fall, winter }
You just need to create new object with this sorting.您只需要使用此排序创建新的 object。
const inventory = { fall: { 'Category 1': [], 'Category 2': [] }, spring: { 'Category 1': [], 'Category 3': [] }, winter: { 'Category 3': [], 'Category 4': [] }, summer: { 'Category 4': [], 'Category 5': [] } } const { fall, spring, winter, summer } = inventory; const sortingInventory = { spring, summer, fall, winter, } console.log(sortingInventory)
FOR SORTING ALGHPITICALLY .用于按算法排序。
const inventory = { fall: { 'Category 1': [], 'Category 2': [] }, spring: { 'Category 1': [], 'Category 3': [] }, winter: { 'Category 3': [], 'Category 4': [] }, summer: { 'Category 4': [], 'Category 5': [] } } const result = Object.fromEntries(Object.entries(inventory).sort((a, b) => { return a[0].localeCompare(b[0]) })) console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.