将javascript对象转换为具有特定顺序的数组

时间:2017-10-15 01:06:49

标签: javascript arrays sorting

如何将javascript对象转换为对象数组?数组元素必须由原始对象中的index属性排序:

输入

var o = {
  "0gfbpa1508024708952": {
    title: "hi daughter",
    index: 3
  },
  "b8tl5k1508024741100": {
    title: "hi dad",
    index: 0
  },
  "cxr9x1508024697320": {
    title: "hi son",
    index: 2
  },
  "qua2802469732": {
    title: "hi cousin",
    index: 9007199254740991
  },
  "tck80i1508024731561": {
    title: "hi mom",
    index: 1
  }
};

输出

[
  {id: "b8tl5k1508024741100", title: "hi dad"},        // array index 0
  {id: "tck80i1508024731561", title: "hi mom"},        // array index 1
  {id: "cxr9x1508024697320", title: "hi son"},         // array index 2
  {id: "0gfbpa1508024708952", title: "hi daughter"},   // array index 3
  {id: "qua2802469732", title: "hi cousin"}            // array index 4
]

This question仅对数组的排序/排序有帮助。它没有解释如何(1)将对象键转换为数组对象id属性,以及(2)如何从数组中删除index键。这里有变换,而不仅仅是基于对象键的排序/排序。

1 个答案:

答案 0 :(得分:0)

let o = {
  "0gfbpa1508024708952": {
    title: "hi daughter",
    index: 3
  },
  "b8tl5k1508024741100": {
    title: "hi dad",
    index: 0
  },
  "cxr9x1508024697320": {
    title: "hi son",
    index: 2
  },
  "qua2802469732": {
    title: "hi cousin",
    index: 9007199254740991
  },
  "tck80i1508024731561": {
    title: "hi mom",
    index: 1
  }
},
arr = [];


for (let k in o) {
  let tmp = o[k];
  tmp.id = k;
  arr.push(tmp);
}
arr.sort(function(a,b) { return a.index - b.index; });

for (let k in arr)
  delete arr[k].index;