0

Is there a way to pass a dynamic variable name to a method? I have a 'Get my data' type method, that hatd to return a sorted list, based on a certain field within my array of objects.

GetOrderedList(name = 'DisplayName', order = 'asc') {
    switch (order) {
      case 'desc':
        return this.MyList.sort((childA, childB) => SortingHelper.sortByStringDesc(childA.DisplayName, childB.DisplayName));
      default:
        return this.MyList.sort((childA, childB) => SortingHelper.sortByStringAsc(childA.DisplayName, childB.DisplayName));
    }
  }

It then calls the javascript sort, which uses my sorting function.

export const sortByStringAsc = (itemStringA, itemStringB) => {
  console.log('Sorting!', itemStringA);
  // If either of the strings are null or blank, just return that no sort is needed.
  if (!itemStringA || !itemStringB) {
    return 0;
  }

  const stringA = itemStringA.toUpperCase();
  const stringB = itemStringB.toUpperCase();

  if (stringA < stringB) {
    return -1;
  }
  if (stringA > stringB) {
    return 1;
  }
  return 0;
};

In the code, I';m hardcoding "childA.DisplayName". But I need to use the "name" variable passed into the method. Is this at all possible?

Craig
  • 18,074
  • 38
  • 147
  • 248

0 Answers0