javascript - 在 JavaScript 中按对象内的对象排序
问题描述
我有一个persons
列表,我按sortColumn
.
const persons = [{
name: "alireza",
family: "seif",
other: {
age: 28,
rate: 30
}
},
{
name: "sara",
family: "niki",
other: {
age: 15,
rate: 15
}
},
{
name: "fateme",
family: "azizy",
other: {
age: 27,
rate: 35
}
}
];
const sortColumn = {
path: "name",
order: "asc"
};
persons.sort((person1, person2) =>
person1[sortColumn.path] > person2[sortColumn.path] ?
sortColumn.order === "asc" ?
1 :
-1 :
person2[sortColumn.path] > person1[sortColumn.path] ?
sortColumn.order === "asc" ?
-1 :
1 :
0
);
console.log(persons);
如果sortColumn.path
是"name"
和order
是"asc"
(或"desc"
),该sort
功能正常工作。但是我该如何排序"other.age"
呢?
谢谢。
解决方案
您可以使用返回排序函数的函数,具体取决于排序顺序。
此排序函数使用另一个函数通过减少到值的拆分路径来从对象中获取值。
const
sortBy = ({ order = 'asc', path }) => order === 'asc'
? (a, b) => ((a, b) => a > b || -(a < b))(getValue(a, path), getValue(b, path))
: (a, b) => ((a, b) => b > a || -(b < a))(getValue(a, path), getValue(b, path)),
getValue = (object, keys) => keys.split('.').reduce((o, k) => o[k], object),
persons = [{ name: "sara", family: "niki", other: { age: 15, rate: 15 } }, { name: "alireza", family: "seif", other: { age: 28, rate: 30 } }, { name: "fateme", family: "azizy", other: { age: 27, rate: 35 } }];
console.log(persons.sort(sortBy({ path: "name", order: "asc" })));
console.log(persons.sort(sortBy({ path: "other.rate", order: "desc" })));
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- android - Facebook 自定义 url 方案
- java - 无法运行小程序,java.security.AccessControlException:访问被拒绝
- python - 从一个基于 .csv 的文件夹中复制特定文件
- business-intelligence - Microstrategy: Force metric level. Attribute + Report level
- git - What is the recommended hotfixing flow with Git?
- visual-studio - I can't access the preference page in Visual Studio 2019
- go - How to understand the macro, get_tls, and identifier,TLS, when I read function, runtime·rt0_go?
- apache-spark - How to exclude Header while importing data from a table in PySpark
- python - 元组理解正在产生意外的输出
- azure - 是否有任何特定方法可以在一个 http 请求中从 Azure 存储队列中获取超过 32 条消息