繁体   English   中英

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

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

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

文件:

[
    {
        "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 来获取唯一的供应商,所以在上面的例子中,我想在没有另一个 HBC 的情况下取回 HBC 和 Avrora

我正在尝试什么:

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

但我收到一个错误:

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: "HBC", }, }, { id: 5, name: "document", supplier: { id: 5, name: "HBC", }, }, { id: 4, name: "document", supplier: { id: 4, name: "Avrora", }, }, ]; const result = [...new Set(Documents.map((o) => o.supplier.name))]; console.log(result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM