对通过回调传递搜索值的对象进行排序会导致未定义

Sorting over an object passing the search value via a callback results in undefined

I have multiple 'sort options' that id like to pass to make this function re-usable, but all passed strings result in undefined when being used to target the objects key. If I hard code the value - name - then it will sort properly. Thanks!

const sortNames = [
  { name: "Maddox", age: 69 },
  { name: "John", age: 69 },
  { name: "Alex", age: 69 },
  { name: "Mike", age: 69 },
];

const sortSomeStuff = (param) => {
    const result = sortNames.sort((a, b) => {
    const paramA = a.param.toLowerCase();
    const paramB = a.param.toLowerCase();

    if (paramA > paramB) {
      return -1;
     }
    if (paramA < paramB) {
      return 1;
    }
    return 0;
  });
  return result;
 };

console.log(sortSomeStuff("name"));

要使用变量来映射对象,请像这样使用 []。还添加了排序方向。

const sortNames = [
  { name: "Maddox", age: 20 },
  { name: "John", age: 69 },
  { name: "Alex", age: 69 },
  { name: "Mike", age: 69 },
];

const sortSomeStuff = (param, dir="asc") => {
    const result = sortNames.sort((a, b) => {
    var paramA = a[param].toString().toLowerCase();
    var paramB = b[param].toString().toLowerCase();
    if(dir=="dsc"){
      paramA = b[param].toString().toLowerCase();
      paramB = a[param].toString().toLowerCase();
    }
    if (paramA < paramB) {
      return -1;
     }
    if (paramA > paramB) {
      return 1;
    }
    return 0;
  });
  return result;
 };

console.log(sortSomeStuff("age","dsc"));