0

Let's say I have an array of objects like this:

[
{name:"Mark",surname:"Smith",age:25,status:1},
{name:"Joe",surname:"Hill",age:21,status:7},
{name:"John",surname:"Grant",age:29,status:14},
{name:"Luke",surname:"Davids",age:22,status:9}
]

and I want to sort it by name with something like this:

sort(function(a, b) {
        var textA = a.name.toUpperCase();
        var textB = b.name.toUpperCase();
        return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
    })

and it works perfectly fine. But what happens if I don't know the key name directly, and I want to sort it?

I get the key name in a prop, so, in my webApp, if a user clicks on a column in a grid, I get the column name. For example, if he clicks on a surname column, I don't know how to put the 'surname' in my sorting function:

let clickedColumnName = props.column.field;
      data=JSON.parse(sessionStorage.getItem('rnList')).RNList.sort(function(a, b) {
      var textA = a.<clickedColumnName>.toUpperCase();// --> how to put a variable here??
      var textB = b.<clickedColumnName>.toUpperCase();// --> how to put a variable here??
        return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
    });
OmarLittle
  • 423
  • 1
  • 9
  • 18

0 Answers0