嵌套对象数组上的 Lodash orderBy

Lodash orderBy on nested Arrays of objects

有一个包含一些嵌套属性的对象数组:

const sports = [{
  name: "Basketball",
  leagues: [{
     createdAt: 1
  }, {
     createdAt: 2
  }]
},{
  name: "Soccer",
  leagues: [{
     createdAt: 3
  }, {
     createdAt: 4
  }]
}]

要获取按名称 DESC (Z->A) 排序的对象数组(非嵌套 属性),我这样做:

const sorted = _.orderBy(sports, item => item.name, ['desc']); 

结果是

[{ name: "Soccer", ... },{ name: "Basketball", ... }] 

我想要实现的是根据对象的嵌套数组对该对象进行排序 leagues.createdAt DESC(假设 1,2,3,4 是正确的时间戳):

[{
  name: "Soccer",
  leagues: [{
     createdAt: 4
  }, {
     createdAt: 3
  }]
},{
  name: "Basketball",
  leagues: [{
     createdAt: 2
  }, {
     createdAt: 1
  }]
}]

试过那样做:

const sorted = _.orderBy(sports, [(item) => item.leagues[0].createdAt], ["desc"])

但是顺序不太对:

您需要映射有序数组,并使用 _.orderBy()leagues 进行排序。我正在使用 _.flow() 创建一个函数,该函数首先对整个数组进行排序,然后映射并排序每个对象中的 leagues

const { flow, orderBy, map } = _

const fn = flow(
  arr => orderBy(arr, 'name', 'desc'),
  arr => map(arr,  ({ leagues, ...o }) => ({
    ...o,
    leagues: orderBy(leagues, 'createdAt', 'desc')
  }))
)

const sports = [{"name":"Basketball","leagues":[{"createdAt":1},{"createdAt":2}]},{"name":"Soccer","leagues":[{"createdAt":3},{"createdAt":4}]}]

const result = fn(sports)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>