Using Vue JS to apply a filter to data fetched from an API

Within my code, I attempted to retrieve users with the role of Admin and only their usernames from the API JSON data. However, I encountered an issue where it did not work as expected.

"response": [
        {
            "profile_picture": "",
            "verified_by_email": false,
            "_id": "61c3a765c5f55200049de490",
            "username": "user2",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83f6f0e6f1b2c3fae2ebececade0ecee">[email protected]</a>",
            "password": "$2a$10$pMOyjwVf1RkaIeVdNKWdaucVRybsDEEN3fjxLZOctJyL42HqrlRgC",
            "role": "User",
            "phone_number": "12365478",
            "createdAt": "2021-12-22T22:32:05.034Z",
            "updatedAt": "2021-12-22T22:32:05.034Z",
            "__v": 0
        },
        {
            "profile_picture": "",
            "verified_by_email": false,
            "_id": "61c325ea02526b000424929f",
            "username": "nina",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97f9fef9d7eef6fff8f8b9f4f8fa">[email protected]</a>",
            "password": "$2a$10$steP5Aq9mcTIA8XLjm9Y5ONoWQUMEWLD7TJPSHzTksqbOTpv9MbD.",
            "role": "Admin",
            "phone_number": "123456",
            "createdAt": "2021-12-22T13:19:38.240Z",
            "updatedAt": "2021-12-22T13:19:38.240Z",
            "__v": 0
        }
    ]
}
computed:{
getAdmin(){
// I stored the API response in the Users array

this.Users.filter(users => {
          return users.role;
}
}
}

Answer ā„–1

To implement the functionality, you must return from the getAdmin function and include a comparison within the filter to check for the Admin role.

computed:{
  getAdmin(){
    return this.Users.filter(user =>  user.role === 'Admin')
  }
}

Modified based on the updated question:

computed:{
  adminNames(){
    return this.Users.filter(user =>  user.role === 'Admin').map(user =>  user.username)
  }
}

Revised according to the feedback received:

If you anticipate only one Admin user at a time, you could use the following approach:

computed:{
  adminName(){
    const admin = this.Users.find(user => user.role === 'Admin')
    return admin && admin.username

    // or using optional chaining
    // return this.Users.find(user => user.role === 'Admin')?.username
  }
}

Answer ā„–2

Utilize a combination of filter and map functions to achieve the desired outcome.

var users = 
{
"response": [
        {
            
            "_id": "61c3a765de490",
            "username": "user2",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ffafceafdbecff6eee7e0e0a1ece0e2">[email protected]</a>",
            "password": "$2a$10$pMOyjwVf1RkaIeVdNKWdaucVRybsDEEN3fjxLZOctJyL42HqrlRgC",
            "role": "User",
            "phone_number": "12365478",

        },
        {
           
            "_id": "61c325e424929f",
            "username": "nina",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9af4f3f4fbdae3fbf2f5f5b4f9f5f7">[email protected]</a>",
            "password": "$2a$10$steP5Aq9mcTIA8XLjm9Y5ONoWQUMEWLD7TJPSHzTksqbOTpv9MbD.",
            "role": "Admin",
            "phone_number": "123456",
           
        }
    ]
}

// Retrieve all admins
var admins = users['response'].filter((user) => user.role === 'Admin').map((user) => user.username)

console.log(admins)

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

Error message encountered: "myData undefined while executing server in Node.js"

const express = require('express'); const app = express(); app.post('/', (req, res) => { let newData = new contact(req.body); newData.save() .then(() => { res.send("Data has been successfully saved to ...

Why does the ng-click function fail to execute when using the onclick attribute in AngularJS?

Whenever I try to invoke the ng-click function using onClick, I encounter an issue where the ng-click function is not being called. However, in my scenario, the model does open with the onClick function. //Function in Controller $scope.editProductDetail ...

How can I create an onclick link within an alert message using JavaScript, even when the alert is not consistently displayed?

I am facing an issue with an alert that is supposed to appear under specific conditions on my website. The alert includes a link that should trigger some code when clicked. However, I keep getting an error message saying "ReferenceError: doTheThing is not ...

What is the procedure for initiating a POST request when the payload is ready for submission?

After a successful payment, my success page is displayed with a URL that includes a query parameter. I want to make a POST request to my API endpoint when the page loads, but I'm encountering an issue where the first POST request is empty (router.quer ...

Duplicate key error occurred in the collection resulting in Error Handling: E11000

Encountering an issue with the user model I'm utilizing alongside Mongoose and MongoDB to create profiles in my database. The process works smoothly when posting a single user, but throws an error upon logging out and attempting to add another: { ...

"Exploring the versatility of using variables in jquery's .css

Iā€™m facing an issue where I need the rotation of a div to be based on the value stored in "anVar." This is what I currently have: function something() { $('.class').css('-webkit-transform:rotate('anVar'deg)') } The desi ...

In order to ensure JavaScript can be universally applied to all images, it needs to be made more generic

I have developed JavaScript functions to enable zoom in and zoom out functionality for an image through pinching gestures. Now, I aim to refactor the code below so that I can include it in a shared JavaScript file. var scale = 1; var newScale; ...

AngularJS view does not wait for the completion of $http.get request

Within my controller, the code snippet below is present... $scope.products = dataService.getJsonData(); console.log($scope.products); The corresponding code in my dataservice is as follows: .service('dataService', function ($http) { t ...

Accessing the data from an HTML5 slider using JQuery

Having some difficulty fetching a value from an HTML5 slider using JQuery. Here is my code snippet: JQuery Code: // Getting the value from slider one $("#submit").on("click", function(evt) { var sliderValue = $('#slider01').attr('value ...

Switch from using pure JavaScript to jQuery or back

While I can navigate through jquery, javascript is a bit more challenging for me. I have a simple function that's coded in javascript, but I need to update the selectors. Changing them in jquery wouldn't be a problem for me, but it's tricki ...

The close button is not functioning properly

I created a script to close my div element by clicking on the 'x' icon, but instead of deleting the div only, the whole page gets deleted. I'm not sure where I went wrong, can anyone help me? HTML <div class="note"> <span id ...

When forcibly closing a window, the disconnect event for Socket.IO sockets may not trigger as expected

Currently in the process of creating chat rooms with Socket.io. I've had good success so far, as it's user-friendly and well-documented. However, I've noticed that if I reload the page, wait for the socket to connect, and then close the w ...

Refreshing a PNG file without the need to refresh the entire page

Developed a captcha using imagestring imagestring($image, 5, 5, 30, $text, $text_color); imagepng($image,"captcha_image.png"); imagepng($image,"captcha_image.png"); The code snippet above shows part of the implementation. <img ...

Why is the value of auth.loggedIn different in the middleware file compared to the template section after a successful login using loginWith in Nuxt JS Auth?

Recently, I delved into learning NuxtJS and I am eager to incorporate authentication using the auth module for Nuxt. It's quite peculiar that logging in with 'loginWith' seems to be functioning well; I can retrieve data about the logged-in u ...

Only the initial TinyMCE editor that was added dynamically is visible, the rest are not showing

I am currently developing a javascript application that will showcase a real-time discussion thread. The app will regularly communicate with the server to fetch new data and display it on the page. To enable users to post comments and replies, we have deci ...

Customize marker icon in Vue when clicked

Is it possible to change the marker icon by clicking on it using vue2-google-maps? I've tried writing some code, but it's not working as expected. Here is the template: <gmap-map ref="mainMap" :center="startLocation" ...

The functionality of linear mode seems to be malfunctioning when using separate components in the mat-horizontal-stepper

In an effort to break down the components of each step in mat-horizontal-stepper, I have included the following HTML code. <mat-horizontal-stepper [linear]="true" #stepper> <mat-step [stepControl]="selectAdvType"> <ng-template matStep ...

What is the reason behind Intellij Code Inspection indicating that a selector is not being used?

I have a small project consisting of two files located in the same folder. App.css .App-align-left { text-align: left; } App.js import React from 'react'; import 'App.css'; class App extends React.Component { constructor(p ...

Regenerate main JavaScript files in Gulp whenever partials are edited

In my gulp task for javascript files, I included partial js files in the source and filtered them out to avoid building them unnecessarily. gulp.task("js", () => { return gulp .src([ src_js_folder + "*.js", src_js_f ...

Are there any testing frameworks available for JavaScript that are similar to Junit and specifically designed for testing object-oriented JavaScript within Node

What are some recommended methods for testing object-oriented JavaScript in Node.js? For instance, let's consider the following Cat.js class: function Cat(age, name) { this.name = name || null; this.age = age || null; } Cat.prototype.getAge ...