I have an object list data like as
data:
[
{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "Eliseo@gardner.biz",
"body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
},
{
"postId": 1,
"id": 2,
"name": "quo vero reiciendis velit similique earum",
"email": "Jayne_Kuhic@sydney.com",
"body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
}
]
I want to get name value from data.
code:
return(
<Fragment>
{Object.keys(cardData).map((keys)=>{
<li>{cardData[keys].name}</li>
})}
</Fragment>
)
but I don't get any data in return. When I use map to iterate it. An error shows me cardData.map is not a function. please help me for solve the problem
Couple of problems:
You need to explicitly add a return statement in the callback function of the map() method
return <li>{cardData[keys].name}</li>
cardData seems to be an array. If that's the case, then no need to use Object.keys(...). Call map() method directly on the array
{cardData.map((obj) => {
return <li>{obj.name}</li>
})}
Alternate option is to remove the curly brackets. This will allow you to remove the return keyword and the li will be returned implicitly
{cardData.map((obj) => <li>{obj.name}</li>)}
Note: Don't forget to add the key prop on the li element:
{cardData.map((obj) => (
<li key={obj.id}>{obj.name}</li>
))}
If cardData is not an array, and is just an object of the following form:
{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
...
}
then use the following code:
{Object.keys(cardData).map(key => {
return <li>{cardData[key].name}</li>
})}
OR use the implicit return by removing the curly brackets:
{Object.keys(cardData).map(key => (
<li>{cardData[key].name}</li>
))}
You have to explicitly return values from map.
Since cardData is already an array so you can use map directly on arrays, no need to take the keys and then process them to get the name.
<>
<ul>
{cardData.map((o) => {
return <li key={o.id}>{o.name}</li>;
})}
</ul>
</>
Works like a charm !
export default function App() {
var cardData = [
{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "Eliseo@gardner.biz",
"body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
},
{
"postId": 1,
"id": 2,
"name": "quo vero reiciendis velit similique earum",
"email": "Jayne_Kuhic@sydney.com",
"body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
}
];
return (
<div className="App">
{Object.keys(cardData).map((keys)=> {return <li>{cardData[keys].name}</li>})}
</div>
);
}