I have an object skills
and I want to iterate over it and map its contents. The object looks like this:
{
"_id": {
"$oid":"5d85b311e180652980824193"
},
"date":{
"$date":{ "$numberLong":"1569043209148" }
},
"title": "test",
"image":"test image",
"description":"test desc",
"__v":{
"$numberInt":"0"
}
}
I am using MongoDB and my mapping looks like this:
componentDidMount() {
this.props.fetchSkills();
}
render() {
const { skills } = this.props
let skillData
if (skills.length === 0) {
return (
<p>There are no skills to display</p>
)
} else {
skillData = skills.map(skill => (
<div key={skill._id}>
<div>
<img src={skill.image} alt="" />
</div>
<div>
<h2>{skill.title}</h2>
<div>
<span>{skill.date}</span>
</div>
<div>
<p>{skill.description}</p>
</div>
</div>
</div>
))
}
return (
<div>
{skillData}
</div>
)
}
However, I get this error when I load the page:
TypeError: skills.map is not a function
26 | )
27 | } else {
28 |
> 29 | skillData = skills.map(skill => (
30 | ^
31 | <div className="item" key={skill._id}>
32 |
I think it's because .map can only iterate through arrays but I am trying to iterate through an object.
You need to have an array
, to be able to iterate through it using the function .map()
So simply transform your object
in an array of objects
like this:
[
{
"_id": {
"$oid":"5d85b311e180652980824193"
},
"date":{
"$date":{ "$numberLong":"1569043209148" }
},
"title": "test",
"image":"test image",
"description":"test desc",
"__v":{
"$numberInt":"0"
}
}
]
And now you'll be able to successfully use .map()