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