eliminate redundant values from an array while utilizing Laravel Eloquent relationship in Vue.js

I have a collection of documents in Laravel that includes objects due to eloquent relationships. The structure of the array is as follows:

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",
        }
    }
]

I am aiming to extract unique supplier names using lodash. In the example above, I would like to retrieve H.B.C and Avrora without duplicates.

This is my attempt:

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

However, an error occurs:

Cannot read properties of undefined (reading 'map')

Answer №1

Error alert: Trying to access properties of an undefined object, specifically 'map'

Essentially, the issue is that you are using the method map on something that is not defined. In this case, you are calling it on:

this.Documents.supplier

This implies that supplier does not exist as a property within this.Documents. Indeed, this is correct since this.Documents is an array of objects with a supplier, but the array itself does not have a supplier property.

Perhaps what you intended to do was:

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

With this modification, each document will be mapped to its supplier's name, and then uniq will be called on the resulting array of supplier names.

Answer №2

When trying to access the supplier property on the this.Documents object, an error occurs because it does not exist.

this.Documents.supplier.map(({ name }) => name)

To fix this issue, you need to map over the entire this.Documents object instead of just the this.Documents.supplier:

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

Alternatively, you can also update the mapping function as follows:

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

Please note: You can achieve the same result without using lodash by utilizing vanilla JavaScript:

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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transferring a JSON array from Google App Engine to Cloud Storage using GO

I am attempting to upload a JSON array to Google Cloud Storage, which is posted by an App Engine application using the code below: saveData : function saveData() { var _this = this, save = this.shadowRoot.querySelector('#save-data'), ...

The pagination feature is malfunctioning and is displaying all elements on every page instead of correctly displaying a

I am currently working with BootstrapVue 3 to create a component that uses a b-table. The issue I am facing is with the pagination functionality using b-pagination. My intention was to display only 2 objects per page, but instead of that, all objects are ...

There was an issue encountered while attempting to utilize orgchart: The property '_aZ' of null could not be read

I've been exploring the use of an organization chart library from Everything goes smoothly with a few nodes, but when I attempt to load the entire organization (approximately 1100 subjects with multiple nested levels), I encounter this console error: ...

Tips for assigning the initial value in a "useState" function to either true or false using the "useEffect" function in React

I'm currently facing an issue with my code. The objective of the code snippet below is to fetch a JSON response from the backend and based on that response, set the "data" in the useState function to either true or false. The problem arises when I cli ...

Web Page Content Scrambling/Character Exchange

I've encountered a perplexing issue that seems to strike randomly, yet I've managed to replicate the problem on three different desktops. Oddly enough, some other desktops never experience this issue and I'm at a loss as to what could be cau ...

Retrieve the corresponding value from the array based on the input value

I have an array that looks like this: var daysArray = [ { DayValue: '10D', DayDisplay: '10' }, { DayValue: '20D', DayDisplay: '20' }, { DayValue: '30D', DayDisplay: '30' } ] Now, the ...

What is the best way to incorporate Vue.js into a Django project?

We are currently working on a school project that involves creating a complete website using Django and Vue. However, we are facing challenges when it comes to integrating Vue into our Django project. In order to simplify things, we have decided to use Vu ...

Using a variety of images to fill various shapes on a grid canvas

I'm currently working on creating a hexagonal grid using canvas, with the goal of filling each tile with a unique pattern taken from an image. However, the code I have written seems to be applying the same image pattern to every tile in the grid, resu ...

visit a new page with each reload

Can I navigate to a new page without refreshing the current window.location.href? I attempted to achieve this using a jQuery event handler on the window object, however, it doesn't seem to be functioning properly. $(window).on('reload', fu ...

Retrieving all options from a dropdown list in HTML using ASP.net C#

I am currently working with a select list that looks like this: <select name="Section" id="Section" size="5"> <option>Section1</option> <option>Section2</option> <option>Section3</option> <option>Section4< ...

Validate whether the path parameter in NextJS is null or empty before executing the query

Currently seeking a method to determine if the query value is empty using the path parameter approach. Have a file named pages/search/[variable1].js Below is the code snippet: import { useRouter } from "next/router" const Variable= () => { ...

Resizing Bootstrap Modal using React with a Personalized Dimension

Is there a way to manually set the width of Bootstrap's Modal React component on my website? I want to be able to define the width in pixels, and if possible, use a const object in the .jsx file for CSS. If not, I can resort to using a .css file. Be ...

Problem with Angular: ng-show not constantly re-evaluating expression

Utilizing a variable named activeScope to manage the state and toggle between two forms. This variable updates its value when a tab is clicked, triggering changeScope. While the change in active states for the tab buttons registers correctly, the divs for ...

What is the process for invoking a websocket from an HTML client?

I have created a WCF Service using netHttpBinding binding and it is hosted on IIS 8 (Windows Server 2012). The interfaces for the service are as follows: [ServiceContract(CallbackContract = typeof(IDuplexCallbackContract))] public interface IHelloWebSocke ...

Postprocessing with a basic shader in Three.js

I've been attempting to create a basic shader for adding noise, but I'm encountering difficulty retrieving the uv coordinates with my current setup. Fragment Shader: uniform float seed; uniform sampler2D pass; varying vec2 vUv; void main (){ ...

Using vue.js to pass route parameters to a component

I'm encountering an issue with passing a route param directly into a component. Despite following various sets of instructions from the documentation (including using the Composition API as shown in the code snippet below), I continue to receive undef ...

Utilizing WebView for Initiating AJAX Calls

One common question often asked is whether it's possible to make ajax requests using a webview. In my case, the UI will consist entirely of native Android code, but I still need to interact with the backend using ajax calls. Fortunately, I am well-ver ...

The error 'sh: dist: unknown operand' occurs when Doclerizing a Vue App

After following the Vue.js Docker tutorial, I encountered an unusual error message. 'sh: dist: unknown operand' This is the content of my Dockerfile: FROM node:lts-alpine RUN npm install -g http-server WORKDIR /app COPY package*.json ./ RUN ...

Traversal of a binary tree in the order of visitation specified by the In

My task was to create a function that traverses a binary tree and returns an array of all its values in inorder. The code provided is: interface BinTree { root: number; left?: BinTree; right?: BinTree; }; const TreeInArray =(t:BinTree):number[] =>{ ...

The Ajax request was a success, but I am unable to retrieve radio button values from the $_POST variable

My website operates fully asynchronously, generating and destroying HTML elements on button clicks that prevent navigation. In this section, I am creating a form with an array of radio boxes for rating from 1 to 10. This form is submitted using jQuery.aja ...