在 vuejs 中使用 laravel eloquent 关系时从数组中删除重复项

remove duplicates from an array when using laravel eloquent relationship in vuejs

因此,由于 laravel 中的 eloquent 关系,我有一个数组,其中包含一个对象。所以数组看起来像这样:

文件:

[
    {
        "id": 6,
        "name": "document",
        "supplier": {
            "id": 5,
            "name": "H.B.C",
        }
    },
    {
        "id": 5,
        "name": "document",
        "supplier": {
            "id": 5,
            "name": "H.B.C",
        }
    },
    {
        "id": 4,
        "name": "document",
        "supplier": {
            "id": 4,
            "name": "Avrora",
        }
    }
]

现在我正在尝试使用 lodash 来获得独特的供应商所以在上面的例子中我想回来 H.B.C 和 Avrora 没有另一个 H.B.C。

我在尝试什么:

CollectionSuppliers () {
    return uniq(this.Documents.supplier.map(({ name }) => name))
},

但是我收到一个错误:

Cannot read properties of undefined (reading 'map')

Cannot read properties of undefined (reading 'map')

这意味着您调用的 map 是未定义的。您正在调用它:

this.Documents.supplier

所以这意味着 supplier 不是 this.Documents 的 属性。这是真的!因为 this.Documents 是具有 supplier 的对象的 数组 ,但数组本身没有 supplier.

您可能想做的是:

return uniq(this.Documents.map(doc => doc.supplier.name))

这会将每个文档映射到供应商名称,然后对供应商名称数组调用 uniq

您正在访问 this.Documents 对象上的 supplier,但它不存在,因此会产生错误

this.Documents.supplier.map(({ name }) => name)

您必须在 this.Documents 上映射,而不是在 this.Documents.supplier 上映射:

CollectionSuppliers() {
  return uniq(this.Documents.map((o) => o.supplier.name));
}

CollectionSuppliers() {
  return uniq(this.Documents.map(({ supplier: { name } }) => name));
}

注意:你不需要 lodash,你也可以使用 vanilla JS 获得独特的元素:

const Documents = [
  {
    id: 6,
    name: "document",
    supplier: {
      id: 5,
      name: "H.B.C",
    },
  },
  {
    id: 5,
    name: "document",
    supplier: {
      id: 5,
      name: "H.B.C",
    },
  },
  {
    id: 4,
    name: "document",
    supplier: {
      id: 4,
      name: "Avrora",
    },
  },
];

const result = [...new Set(Documents.map((o) => o.supplier.name))];
console.log(result);