javascript - 对嵌套的 json 对象进行排序

javascript - sort nested json object

我想通过 "orderby" 键对 javascript 中的以下 json 对象进行排序(有关我需要的输出,请参阅第二个 json 对象):

{
  "1": {
    "category": "Year",
    "value": "2028",
    "title": "Current Year",
    "description": "",
    "orderby": "3"
  },
  "2": {
    "category": "Year",
    "value": "2038",
    "title": "First Year",
    "description": "",
    "orderby": "4"
  },
  "3": {
    "category": "Year",
    "value": "2016",
    "title": "Base Year",
    "description": "",
    "orderby": "1"
  },
  "4": {
    "category": "Year",
    "value": "2018",
    "title": "Previous Year",
    "description": "",
    "orderby": "2"
  }
}

需要的输出:

{
  "3": {
    "category": "Year",
    "value": "2016",
    "title": "Base Year",
    "description": "",
    "orderby": "1"
  },
  "4": {
    "category": "Year",
    "value": "2018",
    "title": "Previous Year",
    "description": "",
    "orderby": "2"
  },
  "1": {
    "category": "Year",
    "value": "2028",
    "title": "Current Year",
    "description": "",
    "orderby": "3"
  },
  "2": {
    "category": "Year",
    "value": "2038",
    "title": "First Year",
    "description": "",
    "orderby": "4"
  }
}

您可以使用 javascript sort 函数对这个数组进行排序。

const data = {
  "1": {
    "category": "Year",
    "value": "2028",
    "title": "Current Year",
    "description": "",
    "orderby": "3"
  },
  "2": {
    "category": "Year",
    "value": "2038",
    "title": "First Year",
    "description": "",
    "orderby": "4"
  },
  "3": {
    "category": "Year",
    "value": "2016",
    "title": "Base Year",
    "description": "",
    "orderby": "1"
  },
  "4": {
    "category": "Year",
    "value": "2018",
    "title": "Previous Year",
    "description": "",
    "orderby": "2"
  }
}
Object.keys(data).sort((a, b) => data[a].orderby - data[b].orderby).map(f => data[f])