我有JSON,每个记录的属性都有单独的对象,我想按属性动态排序。
我设法对属性进行排序,但这是静态代码。我如何动态地制作它?
请在以下位置找到运行代码:https://jsfiddle.net/b8fv4L1z/3/
var json = [
[
{
"apiName": "Name",
"value": "Bob"
},
{
"apiName": "CompanyName",
"value": "Google"
}
],
[
{
"apiName": "Name",
"value": "Micky"
},
{
"apiName": "CompanyName",
"value": "Amazon"
}
],
[
{
"apiName": "Name",
"value": "Donal"
},
{
"apiName": "CompanyName",
"value": "Facebook"
}
]
];
function Comparator(a, b, ) {
if (a[1].value < b[1].value) return -1; // a[1] sort by CompanyName If I put a[0] it will sort by Name.
if (a[1].value > b[1].value) return 1; // a[1] sort by CompanyName If I put a[0] it will sort by Name.
return 0;
}
json = json.sort(Comparator);
console.log(JSON.stringify(json));
预期结果:
(由apiName = CompanyName排序):
[[{"apiName":"Name","value":"Micky"},{"apiName":"CompanyName","value":"Amazon"}],[{"apiName":"Name","value":"Donal"},{"apiName":"CompanyName","value":"Facebook"}],[{"apiName":"Name","value":"Bob"},{"apiName":"CompanyName","value":"Google"}]]
(由apiName = Name排序):
[[{"apiName":"Name","value":"Bob"},{"apiName":"CompanyName","value":"Google"}],[{"apiName":"Name","value":"Donal"},{"apiName":"CompanyName","value":"Facebook"}],[{"apiName":"Name","value":"Micky"},{"apiName":"CompanyName","value":"Amazon"}]]
答案 0 :(得分:3)
比较器具有高阶功能。
tag
答案 1 :(得分:2)
您可以找到想要的属性。也许您需要一个默认值,例如一个空字符串。
function sort(array, apiName) {
const
getValue = array =>
(array.find(o => o.apiName === apiName) || { value: '' }).value;
return array.sort((a, b) => getValue(a).localeCompare(getValue(b)));
}
var array = [[{ apiName: "Name", value: "Bob" }, { apiName: "CompanyName", value: "Google" }], [{ apiName: "Name", value: "Micky" }, { apiName: "CompanyName", value: "Amazon" }], [{ apiName: "Name", value: "Donal" }, { apiName: "CompanyName", value: "Facebook" }]];
console.log(sort(array, 'CompanyName'));
console.log(sort(array, 'Name'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
如果您始终使用相同的数据结构,则可以提前获取apiName
并进行排序,而无需查找每个元素。
function sort(array, apiName) {
const index = array[0].findIndex(o => o.apiName === apiName);
return array.sort((a, b) => a[index].value.localeCompare(b[index].value));
}
var array = [[{ apiName: "Name", value: "Bob" }, { apiName: "CompanyName", value: "Google" }], [{ apiName: "Name", value: "Micky" }, { apiName: "CompanyName", value: "Amazon" }], [{ apiName: "Name", value: "Donal" }, { apiName: "CompanyName", value: "Facebook" }]];
console.log(sort(array, 'CompanyName'));
console.log(sort(array, 'Name'));
.as-console-wrapper { max-height: 100% !important; top: 0; }