Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
How to access role property of userdata which is on mock json server

This is my Json data

{
  "LoginData": [
    {
      "name": "Nick",
      "password": "123",
      "role": "employee"
    },
    {
      "name": "Ratan",
      "password": "123",
      "role": "manager"
    },
    {
      "name": "Rahul",
      "password": "123",
      "role": "admin"
    }
  ]
}

By using filer method with name i get specific data and stored it in variable userData

[{name: 'Rahul', password: '123', role: 'admin'}]

But i cannot access its role using userData.role it gives undefined

what change should i do so that it gives me userData.role === "admin"

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

When you use filter function, you get array in output. You should consider using find method.

Also, I would recommend you to learn about array methods on MDN Docs.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

about 4 years ago · Juan Pablo Isaza Report

0

According to the docs, Array#filter returns:

A new array with the elements that pass the test. If no elements pass the test, an empty array will be returned.

Therefore, you need to access the first element in the returned array first:

const data = {
  "LoginData": [
    { "name": "Nick", "password": "123", "role": "employee" },
    { "name": "Ratan", "password": "123", "role": "manager" },
    { "name": "Rahul", "password": "123", "role": "admin" }
  ]
}

const userData = data.LoginData.filter(({ name }) => name === 'Rahul');
const role = userData[0]?.role;

console.log(role);

If there's always max one item matching, Array#find would be better here:

const data = {
  "LoginData": [
    { "name": "Nick", "password": "123", "role": "employee" },
    { "name": "Ratan", "password": "123", "role": "manager" },
    { "name": "Rahul", "password": "123", "role": "admin" }
  ]
}

const userData = data.LoginData.find(({ name }) => name === 'Rahul');
const role = userData?.role;

console.log(role);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!