如何使用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
相关产品推荐
相关产品推荐

