我有一个JavaScript对象的数组:
var people = [
{
"name": "Edward",
"age": 100,
"wallet": {
"location": "home",
"cash": 500
},
"bank": {
"location": "bank street",
"cash": 22100
}
},
{
"name": "Lisa",
"age": 30,
"wallet": {
"location": "home",
"cash": 20
},
"bank": {
"location": "bank street",
"cash": 12340
}
},
{
"name": "Elisabeth",
"age": 50,
"wallet": {
"location": "home",
"cash": 200
},
"bank": {
"location": "bank street",
"cash": 5000
}
}
];
我该如何按照wallet.cash进行排序?
以下示例(由Ege Özcan提供)可以将这些对象按名称或年龄排序,但是我很难修改它以使用多维键。
function dynamicSort(property) {
var sortOrder = 1;
if(property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a,b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
这个有效:
people.sort(dynamicSort("name"));
这不起作用:
people.sort(dynamicSort("wallet.cash"));
提前感谢你!