首页 > 解决方案 > 在 JavaScript 中按对象内的对象排序

问题描述

我有一个persons列表,我按sortColumn.

const persons = [{
    name: "alireza",
    family: "seif",
    other: {
      age: 28,
      rate: 30
    }
  },
  {
    name: "sara",
    family: "niki",
    other: {
      age: 15,
      rate: 15
    }
  },
  {
    name: "fateme",
    family: "azizy",
    other: {
      age: 27,
      rate: 35
    }
  }
];
const sortColumn = {
  path: "name",
  order: "asc"
};
persons.sort((person1, person2) =>
  person1[sortColumn.path] > person2[sortColumn.path] ?
  sortColumn.order === "asc" ?
  1 :
  -1 :
  person2[sortColumn.path] > person1[sortColumn.path] ?
  sortColumn.order === "asc" ?
  -1 :
  1 :
  0
);
console.log(persons);

如果sortColumn.path"name"order"asc"(或"desc"),该sort功能正常工作。但是我该如何排序"other.age"呢?

谢谢。

标签: javascriptsorting

解决方案


您可以使用返回排序函数的函数,具体取决于排序顺序。

此排序函数使用另一个函数通过减少到值的拆分路径来从对象中获取值。

const
    sortBy = ({ order = 'asc', path }) => order === 'asc'
        ? (a, b) => ((a, b) => a > b || -(a < b))(getValue(a, path), getValue(b, path))
        : (a, b) => ((a, b) => b > a || -(b < a))(getValue(a, path), getValue(b, path)),
    getValue = (object, keys) => keys.split('.').reduce((o, k) => o[k], object),
    persons = [{ name: "sara", family: "niki", other: { age: 15, rate: 15 } }, { name: "alireza", family: "seif", other: { age: 28, rate: 30 } }, { name: "fateme", family: "azizy", other: { age: 27, rate: 35 } }];

console.log(persons.sort(sortBy({ path: "name", order: "asc" })));
console.log(persons.sort(sortBy({ path: "other.rate", order: "desc" })));
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读