I'm working on react app, and I've called a backend to retrieve data. Data from backend is retrieved with res.status(200).json(user). That call in react is
import React, { useState, useEffect } from 'react';
import UserService from '../services/user.service';
const AdminBoard = () => {
const [content, setContent] = useState('');
useEffect(() => {
UserService.getAdminBoard().then(
(response) => {
setContent(response.data);
},
(error) => {
const _content =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
setContent(_content);
}
);
}, []);
console.log(content);
return (
<div className='container'>
<header className='jumbotron'>
<h4>List of users</h4>
{content &&
content.map((item) => (
<div key={item.username}>
<div className='container p-3 my-3 bg-dark text-white'>
<strong>Username:</strong>
<h4>
<div>{item.username}</div>
</h4>
<strong>Email:</strong>
<h4>{item.email}</h4>
<strong>Role:</strong>
<h4>{item.roles.name}</h4> //I'm not getting role name
</div>
</div>
))}
</header>
</div>
);
};
export default AdminBoard;
Now when i console.log content i get:
0: {name: "New Name", username: "agent", email: "[email protected]", roles: Array(1)}
1: {name: "admin", username: "admin", email: "[email protected]", roles: Array(1)}
etc
How roles looks like when i expand them(sorry for picture I couldn't paste output here):

Now I can easily get my values when I usecontent.map with item.name and integrate them into my code.
But i have a problem when I try to extract value from roles.
Now when i console.log content.roles i get undefined.
I want to get name from this array. But I've tried with many ways:
console.log(content.roles.name) console.log(content.roles['name']) console.log(content.roles[0].name) etc. I've also tried with few forEach loops that i found on StackOverflow but I always get cannot read property something of undefined.
My questions are:
- Is this an array of object or is it object with array of objects?
- Is there a method to access these values without loops?
rolesis an array, so theconsole.log(content.roles[0].name)should be right. But the content is an Array too, so you must usecontent[0]....mapbut why when icontent.mapstill doesn't give me at least whole object?.mapyou have the a single element of the main array, this for example{name: "New Name", username: "agent", email: "[email protected]", roles: Array(1)}. In your example you can use a second map inside the first map on therolesarray.item.roles[0].nameinside a map. I don't need another.map. I also asked people below: How that [0] gives right role name? shouldn't retrieve role name inside [0] array? (in my example how doesn't set name PM for every single role?)item.roles[0].namereturn correct value becauserolesis an array with a single element inside and you use [0] like index for retrieve the first and unique element