You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Lodash对含嵌套数组的数组按嵌套字段排序?

问题分析与解决方案

嘿,我一眼就看出问题所在啦!你在调用_.sortBy的时候写了[name, data.count],这里的data被JS当成了一个未定义的变量,而不是数组元素里的data属性,所以才会报“data is undefined”的错误。别担心,有两种简单的解决办法:

方法1:用字符串路径(Lodash专属简写)

Lodash的sortBy支持直接传字符串形式的嵌套属性路径,这样就能精准访问到data.count啦:

example = () => {
  const exampleArray = [];
  _.forEach(this.state.example[name], (data) => {
    exampleArray.push({name, data });
  })

  // 重点:把data.count改成字符串'data.count'
  const sortedArray = _.sortBy(exampleArray, [name, 'data.count']);
  return sortedArray;
}

方法2:用迭代函数(更灵活通用)

如果以后需要更复杂的排序逻辑,或者不想依赖Lodash的路径语法,直接传一个函数进去,手动返回要排序的字段值就行:

example = () => {
  const exampleArray = [];
  _.forEach(this.state.example[name], (data) => {
    exampleArray.push({name, data });
  })

  // 用函数遍历每个元素,返回对应的排序字段
  const sortedArray = _.sortBy(exampleArray, [
    item => item[name], // 按name排序
    item => item.data.count // 按data.count排序
  ]);
  return sortedArray;
}

小提醒

别忘了_.sortBy是返回新数组,不会修改原数组的哦,所以一定要把排序后的结果赋值给新变量再返回,不然原数组还是原来的顺序~要是想按降序排data.count,可以用_.orderBy指定方向:

// 先按name升序,再按data.count降序
const sortedArray = _.orderBy(exampleArray, [name, 'data.count'], ['asc', 'desc']);

内容的提问来源于stack exchange,提问作者Jackson Miller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:59:24