在javascript中按子数组属性值对对象数组进行排序
Posted
技术标签:
【中文标题】在javascript中按子数组属性值对对象数组进行排序【英文标题】:Sort array of objects by subarray property value in javascript 【发布时间】:2015-09-02 10:39:53 【问题描述】:我有一个 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"));
提前谢谢你!
【问题讨论】:
【参考方案1】:您可以将两个不同的参数传递给 dynamicSort 函数
function dynamicSort(property1,property2)
var sortOrder = 1;
if(property1[0] === "-")
sortOrder = -1;
property1 = property1.substr(1);
return function (a,b)
var result = (a[property1][property2] < b[property1][property2]) ? -1 : (a[property1][property2] > b[property1][property2]) ? 1 : 0;
return result * sortOrder;
然后调用
dynamicSort("wallet","cash");
演示
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
];
function dynamicSort(property1,property2)
var sortOrder = 1;
if(property1[0] === "-")
sortOrder = -1;
property1 = property1.substr(1);
return function (a,b)
var result = (a[property1][property2] < b[property1][property2]) ? -1 : (a[property1][property2] > b[property1][property2]) ? 1 : 0;
return result * sortOrder;
alert(JSON.stringify(people.sort(dynamicSort("wallet","cash"))))
【讨论】:
谢谢你!这正是我想要的。然而,第一个代码部分缺少属性 -> property1 更改。【参考方案2】:您可以使用this *** answer 中的Object.byString
方法并像这样修改您的代码:
function dynamicSort(property)
var sortOrder = 1;
if(property[0] === "-")
sortOrder = -1;
property = property.substr(1);
return function (a,b)
var avalue = Object.byString(a, property);
var bvalue = Object.byString(b, property);
var result = (avalue < bvalue) ? -1 : (avalue > bvalue) ? 1 : 0;
return result * sortOrder;
【讨论】:
【参考方案3】:从here提这个比较函数,你可以这样做:
function compare(a,b)
if (a.wallet.cash < b.wallet.cash)
return -1;
if (a.wallet.cash > b.wallet.cash)
return 1;
return 0;
var people = [...];
console.log(people.sort(compare));
【讨论】:
以上是关于在javascript中按子数组属性值对对象数组进行排序的主要内容,如果未能解决你的问题,请参考以下文章