Home > OS >  How to access role property of userdata which is on mock json server
How to access role property of userdata which is on mock json server

Time:01-09

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"

CodePudding user response:

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

CodePudding user response:

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);

  •  Tags:  
  • Related