gpt4 book ai didi

javascript - javascript中按子数组属性值对对象数组进行排序

转载 作者:行者123 更新时间:2023-11-28 07:15:24 24 4
gpt4 key购买 nike

我有一个 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"));

提前谢谢您!

最佳答案

您可以将两个不同的参数传递给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"))))

关于javascript - javascript中按子数组属性值对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30887448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com