Sorting associative array of objects in javascript

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 14:43:56

问题


I have a particular array of objects in js that represent columns of a table. My object is:

var columns = {
  "image": {
    "show": false,
    "orderable": true,
    "value": 0,
    "displayOrder":2
  },
  "name": {
    "show": true,
    "orderable": true,
    "value": 1,
    "displayOrder":0
  },
  "company": {
    "show": false,
    "orderable": false,
    "value": 2,
    "displayOrder":1
  }
}

I have to order the object by "displayOrder", but using a function like

columns.sort(function(a, b) {
  return parseFloat(a.displayOrder) - parseFloat(b.displayOrder); 
});

obviously it return an error. How i can do this?


回答1:


You may use .sort only on arrays due to it is Array.prototype method (MDN). So as an easiest solution I would prefer to reform your columns data from object to array:

var columnList = [
    {
      "key": "image",
      "value": {
          "show": false,
          "orderable": true,
          "value": 0,
          "displayOrder":2
      }
    },
    {
      "key": "name",
      "value": {
          "show": true,
          "orderable": true,
          "value": 1,
          "displayOrder":0
      } 
    },
    {
      "key": "company",
      "value": {
          "show": false,
          "orderable": false,
          "value": 2,
          "displayOrder":1
      } 
    }
];

var result = columnList.sort(function(a, b) {
    return parseFloat(a.value.displayOrder) - parseFloat(b.value.displayOrder);  
});

console.log(result);

The result of console.log would be exactly

0:{key: "name", value: {…}}
1:{key: "company", value: {…}}
2:{key: "image", value: {…}}

This transformation (from object to array) could be done programmatically via Object.keys:

result = Object.keys(columns)
  .map(c => ({ key: c, value: columns[c]}))
  .sort((a, b) => a.value.displayOrder - b.value.displayOrder)

Here the columns is your initial object. With the help of Object.keys() and .map() I turn it into the array I described before, so the .sort() method could be called in a chain.



来源:https://stackoverflow.com/questions/46849294/sorting-associative-array-of-objects-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!