简体   繁体   English

在javascript中对对象的关联数组进行排序

[英]Sorting associative array of objects in javascript

I have a particular array of objects in js that represent columns of a table. 我在js中有代表表列的特定对象数组。 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 我必须通过“ displayOrder”对对象进行排序,但是要使用类似

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

obviously it return an error. 显然,它返回一个错误。 How i can do this? 我该怎么做?

You may use .sort only on arrays due to it is Array.prototype method ( MDN ). 您只能在数组上使用.sort ,因为它是Array.prototype方法( MDN )。 So as an easiest solution I would prefer to reform your columns data from object to array: 因此,作为最简单的解决方案,我希望将columns数据从对象转换为数组:

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 console.log的结果将完全相同

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 : 这种转换(从objectarray )可以通过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. 在这里, columns是您的初始对象。 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. Object.keys().map()的帮助下,我将其转换为前面描述的数组,因此可以在链中调用.sort()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM