【问题标题】:remove duplicates from an array when using laravel eloquent relationship in vuejs在 vuejs 中使用 laravel 雄辩关系时从数组中删除重复项
【发布时间】:2021-12-04 13:55:01
【问题描述】:

因此,由于 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 来获取唯一的供应商,所以在上面的示例中我想返回 H.B.C 和 Avrora 没有另一个 H.B.C.

我正在尝试什么:

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

但我得到一个错误:

Cannot read properties of undefined (reading 'map')

【问题讨论】:

    标签: javascript vue.js lodash


    【解决方案1】:

    无法读取未定义的属性(读取“地图”)

    这意味着您调用map 的任何内容都未定义。您正在调用它:

    this.Documents.supplier
    

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

    你可能打算做的是:

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

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

    【讨论】:

      【解决方案2】:

      您正在访问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);

      【讨论】:

        猜你喜欢
        • 2020-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-12
        • 1970-01-01
        • 2018-10-22
        • 2013-09-26
        • 1970-01-01
        相关资源
        最近更新 更多