通过嵌套的动态对象键过滤对象数组

时间:2021-02-02 18:05:33

标签: javascript arrays sorting object

我想通过嵌套键过滤对象数组。

这就是我被卡住的地方:

数据

const dataSet = [{
  firstName: {
    value: 'John'
  },
  lastName: {
    value: 'Doe'
  },
}, {
  firstName: {
    value: 'Alicia'
  },
  lastName: {
    value: 'Keys'
  },
}, ];

方法

const sortData = (sortKey: string, arrayToSort: any[], isASC: boolean) => {
  const compare = (a: any, b: any) => {
    const aValue = String(a[sortKey].value);
    const bValue = String(b[sortKey].value);
    if (isASC) {
      return aValue.localeCompare(bValue, undefined, {
        numeric: isNumeric(aValue),
      });
    }
    return bValue.localeCompare(aValue, undefined, {
      numeric: isNumeric(bValue),
    });
  };
  return [...arrayToSort.sort(compare)];
};

const sortedData = sortData(header, dataSet, true);

但它没有排序...如果我按 firstName 升序排序,我想先得到 Alicia,但 John 总是先到 xD

0 个答案:

没有答案
相关问题