Manipulating arrays and troubleshooting Typescript errors in Vue JS

I am attempting to compare the elements in one list (list A) with another list (list B), and if there is a match, I want to change a property/field of the corresponding items in list B to a boolean value.

Below is the code snippet:

export default defineComponent({
  name: 'Users',
  props: {
      existingUsers : {
          type: Array as PropType<Array<UserModel>>,
      }
  },
  async setup(props) {
    const allUsers = ref<Array<UserModel>>(await userService.list())
    const userList = ref<Array<UserModel>>([{ id: 0, email: '', first_name: '', last_name: '', }])
   
    function defineUsers(): Array<UserModel> {
        if (props.existingUsers) {
            const existingUsers = props.existingUsers;
            userList.value = allUsers.value
            .map((user: UserModel) => existingUsers
            .forEach((us: UserModel) => (us.id === user.id) ? user.isSelected = true : user));
            return userList.value;
        } else {
            userList.value = allUsers.value;
            return userList.value;
        }
    }
    defineUsers();

In summary, if no existing users are passed as props, then userList will be set to allUsers (which obtains data from an API through a GET request). If existing users are provided as props, then each user in allUsers that matches an entry in existingUsers should have its 'isSelected' value set to true.

The error I encountered regarding userList.value on line 3 within the function defineUsers is:

Type 'ComputedRef<void[]>' is missing the following properties from type '{ id: number; email: string; first_name: string; last_name: string; organization?: { id: number; company_name: string; address: string; postal_code: string; city: string; state: string; country: string; vat: string; fiscal_code?: string | undefined; codice_sdi?: string | undefined; registration_date?: string | undef...': length, pop, push, concat, and 28 more.Vetur(2740)

Any insights on how to resolve this issue?

Thank you very much.

Answer №1

To achieve the desired outcome, you cannot directly use the .forEach method as a return type. Instead, consider implementing the following approach:


userList.value = allUsers.value.map((user: UserModel) =>
  existingUsers.map((us: UserModel) => {
    user.isSelected = us.id === user.id;
    return user;
  })
);

Feel free to test this solution and inform me of its effectiveness!

Answer №2

Here is my solution:

function getUsersList(): Array<UserModel> {
    if (props.existingUsers) {
        const existingUsers = props.existingUsers;
        userList.value = allUsers.value.map((user: UserModel) => {
            let isSelected = existingUsers.some((us: UserModel) => 
                us.id === user.id
            );
            user.isSelected = isSelected;
            return user;
        });
        return userList.value;
    } else {
        return allUsers.value;
    }
}
    

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

Managing the clearing of a view component in React or Vue.js

In my project, I have a container component that handles all the business logic, ajax requests, and data management. This container component has child components to which it passes data and methods as props. For example, there is a "CommentForm" compone ...

Can you explain the concept of being "well-typed" in TypeScript?

The website linked below discusses the compatibility of TypeScript 2.9 with well-defined JSON. What exactly does "well-typed" JSON mean? As far as I understand, JSON supports 6 valid data types: string, number, object, array, boolean, and null. Therefore, ...

How to stop empty numbers in angular.js

My goal is to ensure that an input with a required attribute always has some value, and if left empty, defaults to zero. <input ng-model='someModel' required> I have created the following directive: App.directive('input', fun ...

Building a bespoke search input for the DataTables JQuery extension

As the title indicates, I am in the process of developing a custom search box for the DataTables JQuery plugin. The default options do not suit my needs, and configuring the DOM is also not ideal as I aim to integrate it within a table row for display purp ...

Leveraging Prototype's Class creation function to declare confidential and safeguarded attributes and functions

Looking for a solid approach to defining private and protected properties and methods in Javascript? Check out this helpful discussion here on the site. Unfortunately, the current version of Prototype (1.6.0) doesn't offer a built-in method through it ...

Fetch additional data from a table by utilizing Ajax and PHP

I have 7 data entries in my database When attempting to load the data from a table using ajax and php, I encountered an issue. After clicking the "load more" button, the data displays successfully but the "load more" button disappears. Here is my index. ...

Implementing a timed delay before assigning a class in the state

I am trying to implement a delay before applying for a new class. This is my current situation const [isDone, setIsDone] = useState<boolean>(false); Within a method, I have the following code snippet const myMethod = () => { .... .... se ...

An unhandled promise rejection occurred because no routes could be found to match. URL Segment:

I'm facing an issue with my application where it doesn't recognize the route even though I have defined and imported it in app.module. Whenever I try to redirect to a specific route upon data retrieval, I encounter this exception: onSubmit(){ ...

"Utilize the implode function selectively, avoiding the need to apply it to each

I am interested in utilizing the implode function implode(" ",$array);, however, I want to avoid having a space between each individual array element. For instance, if the array consists of $array = array("M.","Benz","wants","to","marry","A.","Marry");, ...

The Flux Router in React Native

I am diving into the world of React Native and currently working on creating a practice app. The issue I'm facing is with the routing functionality in my project. At the moment, I have three main components: the app itself, the router component, and o ...

Is there a way to transfer a variable from Angular 2 Frontend Express JS to an Angular 2 component?

After conducting thorough research, I have made specific modifications to my code. However, I am encountering some errors in my console that I cannot seem to resolve. Despite following a tutorial step by step. Your assistance would be highly valued as I a ...

Issue encountered with websocket connection while attempting to include dependencies

My current project involves integrating charts for the graphical component using React within an Electron software. I've added interaction with buttons (sections) to insert different data into the graphs based on user clicks on one of the sections. Th ...

Delete a Woocommerce item from the shopping cart using ajax/fetch technology

My issue lies with the removal of products from the cart in Woocommerce, specifically involving WC_Cart::remove_cart_item. The error messages I am encountering are: POST http://localhost:3000/esport/wp-admin/admin-ajax.php [HTTP/1.1 500 Internal Server Err ...

Tips for accessing the @keyframes selector and extracting the value from it

In my CSS code, I have a shape element with an animation that spins infinitely for 50 seconds. #shape { -webkit-animation: spin 50s infinite linear; } @-webkit-keyframes spin { 0% { transform: rotateY(0); } 100% { transform: rotateY(-360deg ...

Using node.js version 10.0.0 to tinker with gulp

I was working on a node.js api project that functioned perfectly with node.js v8.1.4 & npm v5.0.3. However, upon transitioning to node.js v10.0.0 & npm v5.6.0, I encountered the following error: [email protected] ecosystem E:\opensource& ...

Learn the best practices for integrating the options API with the Composition API in Vue3

Using vue3 and vite2 Below is a simple code snippet. The expected behavior is that when the button is clicked, the reactive 'msg' variable should change. It works as expected in development using Vite, but after building for production (Vi ...

Comparing the length of an array to whether the length of the array is greater than

What distinguishes checking an array's length as a truthy value from verifying that it is greater than zero? In simple terms, is there any advantage in utilizing one of these conditions over the other: var arr = [1,2,3]; if (arr.length) { } if (arr ...

What is the best way to change the date format from "yyyy-MM-dd" in a JavaScript file to "dd/MM/yyyy" and "MM/dd/yyyy" formats in an HTML file?

Is there a way to transform the date string "2020-08-02" from a JavaScript file into the formats "08/02/2020" and "02/08/2020" in an html file, without relying on the new Date() function in JavaScript? I would greatly appreciate any assistance with this t ...

How to retrieve an object once it exits the viewport in JavaScript

I am seeking guidance on how to reset an object to its initial position (0) once it exits the browser window. Currently, I have an image that moves when you click on the up/down/left/right buttons, but it eventually extends beyond the browser window. Belo ...

Creating dynamic button names and detecting the pressed button in PHP

Right now, I am experimenting with PHP to create a unique project. This experiment is just a small part of a larger file that I am working on. Essentially, the aim is for the program to generate a series of submit buttons within a form, each assigned a dis ...