[英]remove duplicates from an array when using laravel eloquent relationship in vuejs
So I have an array that has an object inside of it due to eloquent relationship in laravel.因此,由于 laravel 中的雄辩关系,我有一个数组,其中包含一个对象。 So the array looks something like this:
所以数组看起来像这样:
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",
}
}
]
Now I'm trying to use lodash to get unique suppliers so in the above example I would want to get back HBC and Avrora without another HBC现在我正在尝试使用 lodash 来获取唯一的供应商,所以在上面的例子中,我想在没有另一个 HBC 的情况下取回 HBC 和 Avrora
What I'm trying:我正在尝试什么:
CollectionSuppliers () {
return uniq(this.Documents.supplier.map(({ name }) => name))
},
but im getting an error:但我收到一个错误:
Cannot read properties of undefined (reading 'map')
Cannot read properties of undefined (reading 'map')
无法读取未定义的属性(读取“地图”)
This means whatever you're calling map
on is undefined.这意味着您调用
map
任何内容都是未定义的。 You're calling it on:您正在调用它:
this.Documents.supplier
so that means supplier
is not a property of this.Documents
.所以这意味着
supplier
不是this.Documents
的属性。 Which is true!这是真的! Because
this.Documents
is an array of objects with a supplier
, but the array itself doesn't have a supplier
.因为
this.Documents
是一个带有supplier
的对象数组,但该数组本身没有supplier
。
What you probably meant to do was:你可能想做的是:
return uniq(this.Documents.map(doc => doc.supplier.name))
This maps each document to just the supplier name, and then calls uniq
on the array of supplier names.这将每个文档映射到供应商名称,然后在供应商名称数组上调用
uniq
。
You are accessing the supplier
on the this.Documents
object, but it doesn't exist, so it produces error您正在访问
this.Documents
对象上的supplier
,但它不存在,因此会产生错误
this.Documents.supplier.map(({ name }) => name)
You have to map over the this.Documents
not on the this.Documents.supplier
as:你必须在地图上
this.Documents
不上this.Documents.supplier
为:
CollectionSuppliers() {
return uniq(this.Documents.map((o) => o.supplier.name));
}
or或者
CollectionSuppliers() {
return uniq(this.Documents.map(({ supplier: { name } }) => name));
}
NOTE: You don't need lodash for this, you can get unique elements using vanilla JS also:注意:您不需要 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.