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

While iterating over each item in the List<string> retrieved from an AJAX GET request in JavaScript

Trying to iterate through a list of strings and display them on the page, but facing an error as described in the title... "Uncaught TypeError: response.forEach is not a function" I've looked into for loops in JavaScript, but they seem to work wit ...

Guide on dynamically loading email contacts options in selectize.js

I have been working with selectize.js to create an email contacts feature. However, I am facing an issue where the mail list retrieved from the database is displaying as undefined in selectize. Strangely, when I manually enter the return value, everything ...

What is the best way to utilize imported classes, functions, and variables within an Angular 2 template?

I've come up with a solution for incorporating static content into a template, but I'm unsure if it's the best approach. I would like to know if there is an official or more efficient method of achieving this. Here's an example showcas ...

Is there a way to incorporate CSS or tables when converting HTML to PDF using JavaScript?

While working on a project, I successfully converted an HTML file into a PDF. However, the output did not display the CSS design. Can anyone provide suggestions on how to include CSS design in the PDF file? Below is the JavaScript function code: $(funct ...

HTTP Interceptor never finishes executing (finalization is never triggered)

In my angular 8 project, I created a basic HttpInterceptor that simply duplicates the original request and includes an additional parameter: @Injectable() export class RequestHeadersInterceptor implements HttpInterceptor { intercept(request: HttpReques ...

An issue has been identified in the bubble sort algorithm causing certain numerical lists to not be properly sorted when implemented in NodeJS

I am just beginning to learn about algorithms and have started with the bubble sort. I wrote my own implementation and it seems to work well most of the time when sorting a list of numbers from 1 to 100. However, occasionally there is one random number th ...

What is the best way to handle mapping an array with uncertain levels of nesting?

My task involves rendering an array of comments in ReactJs, each of which can have nested comments at unknown levels. I am struggling to figure out how to display these comments with their respective nesting levels. comment 1 -- comment 2 -- comment 3 --- ...

Stop Swiper Slide from moving when clicked on

I am currently utilizing Swiper JS and have encountered an issue. In my Swiper slider, each slide contains a button. Whenever I click on the slide or the button itself, the slide becomes the active one, causing the entire slider to move. Is there a way to ...

Displaying images retrieved from firebase on a React.js application

Currently, I am attempting to retrieve images from Firebase storage and then exhibit them in a React component. As a newcomer to React/Javascript, I find it challenging to grasp the asynchronous nature of React/JS. The issue I'm facing is that althoug ...

Running PHP using Node.js | Redirecting with the help of .htaccess

Currently, I am using a Node.js Server with the following configuration: app.use(express.static(__dirname + '/public')); However, I am facing an issue when trying to execute a php file using the XMLHttpRequest function like this: var xhttp = n ...

What's the reason for the alert not functioning properly?

I am curious about the distinction between declaring a variable using var. To explore this, I tried the following code: <body> <h1>New Web Project Page</h1> <script type="text/javascript"> function test(){ ...

ng-repeat is not functioning properly despite the presence of data

Currently, I am in the process of building a basic Website using the MEAN stack, but I'm facing an issue with an ng-repeat that is failing to display any content. Oddly enough, when I attempt something similar in another project, it works perfectly fi ...

Assistance with organizing date schedules using Javascript

I'm currently assisting a friend with his small project, and we've run into an interesting situation. Imagine a scenario where a doctor informs their patient that starting today, they have X number of consultations scheduled for every Wednesday a ...

The build process encountered an error with the sass-loader module and was

After updating Vuetify, my web app seems to be broken. The issue appears to be related to sass-loader despite following all the instructions. The error message received is: Module build failed (from ./node_modules/sass-loader/lib/loader.js): Despite sea ...

Is there a way to assign a unique scrollTop value for a specific scrollspy location?

I have a custom script that tracks the current position within a menu and applies an active class to it. However, I require specific rules for the ID contact_form. Specifically, I need to add 1000px to the scrollTop value for that particular ID location. ...

Tips for including the % symbol in the Y-axis labels on a HighChart graph

I am attempting to incorporate the % symbol after the value of 100 or -100 on the yAxis in the chart shown above. I made an attempt to add the % symbols as follows: quotes.data.frequency_counts[i].negative = Math.round(negative * -1)+'%'; quote ...

Node.js: Troubleshooting a forEach Function Error

I am encountering an issue with my nodejs script that is causing a "function not found" error after trying to insert data from json files into Firestore. How can I resolve this? Thank you for your help. Below is my code snippet: var admin = require("f ...

Tips for Showing a Portion of an Object in React JS

Need help displaying subitems of an object. I can display the main item but struggling with subitems. Here's the attached image for reference: I'm having trouble displaying the comments section in the object. I'm using Django API and trying ...

Passing data from a method callback to a function and returning a variable in the same function

Is there a way to properly return the latlon variable from the codeAddress function? The typical 'return latlon' doesn't seem to work, possibly due to scope issues. Any suggestions on how to resolve this? function codeAddress(addr) { ...

The button's color cannot be modified due to a malfunctioning event script that is not

Seeking an explanation for why my current implementation isn't working. I'm attempting to create a quiz with a multiple choice section where the correct answer turns green when clicked, and incorrect answers turn red. Despite validating the code ...