Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’}]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading