javascript - 如何对具有多组json对象的json数组进行排序
问题描述
我想根据 name 属性对下面的 json 数组进行排序。挑战是如果“行”包含两个 json 数组元素,那么它应该首先在组内做空,然后根据另一个 json 数组进行排序。
这是我的尝试。它正在对数组进行排序,而不是对(组内的元素)进行排序
// sort the data
this.leadPoolRecords = JSON.parse(
JSON.stringify(this.leadPoolRecords)
).sort((a, b) => {
a = a[colName] ? a[colName].toLowerCase() : ""; // Handle null values
b = b[colName] ? b[colName].toLowerCase() : "";
return a > b ? 1 * isReverse : -1 * isReverse;
});
data = [
{
"button": {
"btn": true,
"size": "20"
},
"rows": [
{
"name": "john",
"role": "CEO",
"phone": "xxxxxxxxx",
"email": "bcd@email.com"
}
]
},
{
"button": {
"btn": true,
"size": "20"
},
"rows": [
{
"name": "Mike",
"role": "Director",
"phone": "xxxxxxxxx",
"email": "cde@email.com"
}
]
},
{
"button": {
"btn": true,
"size": "20"
},
"rows": [
{
"name": "rahul",
"role": "CTO",
"phone": "xxxxxxxxx",
"email": "xyz@email.com"
},
{
"name": "ajay",
"role": "Researcher",
"phone": "xxxxxxxxx",
"email": "abc@email.com"
}
]
}
]
解决方案
首先,您可以rows
这样对数组进行排序:
data.forEach(item => item.rows.sort((row1, row2) => row1.name.localeCompare(row2.name)));
data
然后您可以根据rows
数组对元素进行排序。例如,如果要根据name
第一行的 对它们进行排序:
data.sort((item1, item2) => item1.rows[0].name.localeCompare(item2.rows[0].name));
推荐阅读
- python - 如何在 Python 中从文本文件创建文件夹
- javascript - 装饰器不支持 Angular 6 Prod 函数调用,但调用了“..Module”
- c# - 我如何打开表单并通过一个按钮将其关闭
- angular - Angular 6 路由参数
- javascript - 样式显示 none 未在函数中触发
- android - 单击时如何在 MP 饼图中获取 String [] 元素?
- jquery - 无法为 iframe 使用可拖动的 jQuery UI
- jenkins - 通过Jenkins TestComplete 测试参数
- spring - 春季使用@Transactional注解的最佳实践
- gitlab-ci - 在合并请求期间和合并后运行 GitlabCI