簡體   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