问题
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