reactjs 查找键存储在变量中的对象值[duplicate]

bogh5gae  于 2022-12-03  发布在  React
关注(0)|答案(1)|浏览(117)

此问题在此处已有答案

JavaScript object: access variable property by name as string [duplicate](3个答案)
昨天关门了。
假设我有一个对象数组,如下所示:

[
{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}
]

我想按名称排序,如下所示:

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

它运行得很好,但是如果我不知道键名,而我想对它进行排序呢?
我在一个prop中得到了键名,因此,在我的webApp中,如果用户点击了网格中的一列,我就得到了列名。例如,如果他点击了一个姓列,我不知道如何把'姓氏'放在我的排序函数中:

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;
    });
pn9klfpd

pn9klfpd1#

我们可以定义一个动态变量来存储密钥,然后获取类似a[key]的值
注:你最好检查一下类型,如果是数字,我们可以直接比较

const data = [
{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}
]

const sortData = (data,key) => {
  data.sort((a,b) => {
    let textA = a[key];
    let textB = b[key];
    if(isNaN(textA)){
       textA = textA.toUpperCase()
     }
    if(isNaN(textB)){
       textB = textB.toUpperCase()
     }
    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0; 
  })
  return data
}

console.log(sortData(data,'name'))
console.log('-----------------------')
console.log(sortData(data,'age'))

相关问题