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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:18:03