So I have an array that has an object inside of it due to eloquent relationship in 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 H.B.C and Avrora without another H.B.C.
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. You're calling it on:
this.Documents.supplier
so that means supplier is not a property of 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.
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.
You are accessing the supplier on the this.Documents object, but it doesn't exist, so it produces error
this.Documents.supplier.map(({ name }) => name)
You have to map over the this.Documents not on the this.Documents.supplier as:
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:
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);