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

What is the best way to access the front camera on both Android and iOS devices in order to capture a photo using Vue.J

I am currently developing a PWA Vue.Js application and I am trying to implement a feature that allows users to take a picture with the front camera on their mobile devices. Although I have managed to write code that works on my desktop browser, I have bee ...

What is the proper way to delete a callback from a promise object created by $q.defer() in AngularJS?

When working with AngularJS, the $q.defer() promise object has the ability to receive multiple notify callbacks without overwriting previous ones. var def = $q.defer(); def.promise.then(null, null, callback1); def.promise.then(null, null, callback2); If ...

Are there any other options besides using the React Material-UI makeStyles() function for styling class Components?

While experimenting with the makeStyles() function in Material-UI's React library, I encountered a specific error message: The use of hooks is limited to the body of a function component. Below is a snippet of the code that triggered this error: ...

How the Marvel of jQuery Ignites the Power of

I require some assistance with the callbacks. It appears that they are not functioning properly. I am in the process of creating a jQuery-based game. I have designated a <div id='button'></div> for all the buttons that will be used ...

Receiving the [object HTMLInputElement] on the screen rather than a numerical value

I have an input box where a user can enter a number. When they click a button, I want that number to be displayed on the page. However, instead of seeing the number, I am getting the output as [object HTMLInputElement]. Below is my TypeScript code: let qu ...

Transform a dynamic web page into a static one using Next.js

Utilizing Next.js and React.js, I create dynamic web pages. Specifically, I generate user-related web pages that need to be updated when there are changes in the user data. How can I generate static HTML pages from this updated data within Next.js? Are the ...

Listen for events in a child process in NodeJS

I am currently utilizing the node child_process API https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options var child = child_process.spawn(cmd, val, options); Within the child process, I make use of the followin ...

Using Linux variables in the .env file of your Vue.js project can provide a convenient way to

Using .env in a *.js file allowed me to set the BANK variable as either A_BANK or B_BANK like so: BANK=A_BANK or BANK=B_BANK However, when passing the argument as A_BANK or B_BANK like: --bank A_BANK in a shell script loop for var in $@ do if [ ${var} ...

Tips for identifying the correct selectedIndex with multiple select elements present on one page

How can I maintain the correct selectedIndex of an HTMLSelectElement while having multiple select elements in a loop without any IDs? I am dynamically loading forms on a webpage, each containing a select element with a list of priorities. Each priority is ...

Navigating through different sections of your Angular app can be easily accomplished using

My current project structure is set up like this: The application I am working on is hosted in a subdirectory called /my-scripts/vk.plants. This means that when I request this URL, it loads layout.html and returns it to the user. layout.html contains the ...

Selection Change Event for Dropdown Menu

Just starting to learn JavaScript and currently working with 3 select elements on a JSP page: <select id="railwayServiceList" name="railwayService_id" onchange="changeCompaniesCombo()"></select> <select id="companyList" name="company_i ...

JavaScript function for automatic scrolling to the bottom of the page is not functioning as expected

I'm working on incorporating a terminal/console feature into my website. I came across the JavaScript functions for scrolling down a page, namely window.scrollTo(0,document.body.scrollHeight); and window.scrollTo(0,document.querySelector(".fakeSc ...

Issue with sending data from JQuery Ajax to PHP codeExplanation:The problem

Here is the output from myscript.js: [{"orcamento":"10","atual":"20","desvio":"","data":"2015-01-01","nome_conta":"BBB","nome_categoria":"abc","nome_entidade":"def"}] This is the content of myscript.js: if (addList.length) { $.ajax($.extend({}, ajax ...

I'm facing an issue with converting my object to an array as I keep getting the message: "ERROR TypeError: undefined

ERROR TypeError: undefined is not a function Why am I unable to convert my object to an array? This error keeps popping up as I attempt to map all the items that are currently objects but need to be converted into arrays for mapping. How can I accomplish ...

What is the best way to import modules with the "@" symbol in their path when working with Node.js?

Situation In my VueJS project, I have created service modules for use with vue cli. My code makes use of the @ symbol to easily access files within the src folder: /* Inside someService.js */ import API from '@/services/APIService.js' Ch ...

The React Hook useEffect is missing a dependency: 'handleLogout'. Make sure to either add it to the dependency array or remove it from the useEffect hook

import { useState, useEffect } from "react"; import LoginModal from "./LoginModal"; import { NavLink, useLocation, useNavigate } from "react-router-dom"; import { useDispatch } from "react-redux"; import { userLogout ...

Is there an easy method for extracting URL parameters in AngularJS?

Hello, I'm new to Angular and coming from a background in PHP and ASP. In those languages, we typically read parameters like this: <html> <head> <script type="text/javascript"> var foo = <?php echo $_GET['foo&apo ...

When a card is clicked in the parent component, data is sent to the child component in Angular. The card contains an image, name, ID,

How can I pass data from a parent component (nfts) to a child component (main) when a card is clicked? The card contains images, ids, names, and more information. I've attempted using @Input() but haven't been able to receive the value in the ch ...

Problem related to permissions within a node.js package

Introducing my newly built npm module called emeraldfw, now available for public use. Here is a glimpse of the contents in my package.json file: { "name": "emeraldfw", "version": "0.6.0", "bin": "./emeraldfw.js", "description": "Emerald Framework ...

Having trouble with overriding an @media query for material-ui react components?

I've been trying to modify a @media CSS rule on a Material UI component, similar to the discussions on How to over-ride an @media css for a material-ui react component and Override components like MuiTab that use media queries. However, I have not bee ...