如何在Vue中对Laravel Eloquent关联返回的数组实现供应商去重
报错原因及解决方案
错误原因
this.Documents是数组类型,本身不存在supplier属性,因此this.Documents.supplier返回undefined,对undefined调用map方法就会触发你遇到的报错。
正确实现代码
基础实现(适配你给出的示例数据结构)
import { uniq } from 'lodash' CollectionSuppliers () { // 先遍历整个Documents数组提取每个条目的供应商名称,再去重 return uniq(this.Documents.map(docItem => docItem.supplier.name)) }
鲁棒性优化版本(兼容部分条目无供应商的场景)
如果部分Document条目可能不存在supplier关联对象,建议增加过滤逻辑避免出现新的报错:
import { uniq } from 'lodash' CollectionSuppliers () { return uniq( this.Documents // 过滤掉没有有效供应商名称的条目 .filter(docItem => docItem?.supplier?.name) .map(docItem => docItem.supplier.name) ) }
Lodash全工具实现
你也可以直接用lodash的map方法简化深层属性提取的写法:
import _ from 'lodash' CollectionSuppliers () { return _.uniq(_.map(this.Documents, 'supplier.name')) }
内容的提问来源于stack exchange,提问作者iSnuff
相关产品推荐
相关产品推荐

