I have JSON which Each records attributes has seperate object, I want to sort by attributes dynamically.
I am manage to do dthe sorting with attributes, but it's static code. How Could I make it dynamically ?
Please find running code on : 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));
Expected Result:
(Sorted by 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"}]]
(Sorted by 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"}]]
name? you have nested arrays. on which array shoulf the sorting happen?