Lodash:如何从对象数组中获取唯一值,然后按这些唯一值对这些对象进行排序?

the*_*tim 3 javascript lodash

我正在尝试使用 Lodash 从对象数组中获取唯一值,然后使用这些值作为键对对象数组进行排序。我能够找到一个解决方案,但我不确定这是最复杂、最可读或最高效的方法。

使用_.uniq和_.map,我能够country从每个 中获取唯一值artist。然后我循环遍历这些值并按artists它们进行过滤。

let artists = [
  { name: "Bob Jones", country: "Australia"},
  { name: "Jane Smith", country: "Australia"},
  { name: "James Good", country: "USA"},
  { name: "Jeremy Bond", country: "Japan"},
]

let countries = _.uniq(_.map(artists, 'country'))
// ["Australia", "USA", "Japan"]

let res = []

for (let i = 0; i < countries.length; i++) {
  let country = countries[i]
  let obj = {
    country: country,
    artists: artists.filter(artist => artist.country === country)
  }

  res.push(obj)
}

console.log(res)
/* [
  { country: "Australia",
    artists: [
      { name: "Bob Jones", country: "Australia"},
      { name: "Jane Smith", country: "Australia"}
    ]
  },
  { country: "USA",
    artists: [
      { name: "James Good", country: "USA"}
    ]
  },
  { country: "Japan",
    artists: [
      { name: "Jeremy Bond", country: "Japan"}
    ]
  }
]
*/
Run Code Online (Sandbox Code Playgroud)

是否有任何 Lodash 功能可以用来代替 for 循环和对象分配?

Ori*_*ori 6

使用_.groupBy()将艺术家收集到 的对象中{ [country]: artists },然后使用_.map()将对象转换为数组:

const artists = [
  { name: "Bob Jones", country: "Australia"},
  { name: "Jane Smith", country: "Australia"},
  { name: "James Good", country: "USA"},
  { name: "Jeremy Bond", country: "Japan"},
]

const result = _.map(
  _.groupBy(artists, 'country'),
  (artists, country) => ({ country, artists })
)

console.log(result)
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
Run Code Online (Sandbox Code Playgroud)

与lodash/fp相同的解决方案- 用于_.flow()生成函数:

const { flow, groupBy, map, head } = _

const byCountry = flow(
  groupBy('country'),
  map(artists => ({ country: head(artists).country, artists }))
)

const artists = [
  { name: "Bob Jones", country: "Australia"},
  { name: "Jane Smith", country: "Australia"},
  { name: "James Good", country: "USA"},
  { name: "Jeremy Bond", country: "Japan"},
]

const result = byCountry(artists)

console.log(result)
Run Code Online (Sandbox Code Playgroud)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
Run Code Online (Sandbox Code Playgroud)