Reputation: 107
Hello I'm trying to iterate over some data which i got from my Database, it's an Object of Objects
this.state.data: {
someGuy:{
cardHeading:"someHeading"
email:"[email protected]"
begin:"13-02-2018"
end:"15-02-2018"
message:"some Message"
days: "2 Tage"
turnover: 123
url:"someUrl"
},
secondGuy: {
cardHeading:"secondHeading"
email:"[email protected]"
begin:"13-03-2018"
end:"15-04-2018"
message:"second Message"
days: "many days"
turnover: 321
url:"someUrl"
}
}
now i'm trying to map this Data in an react-bootstrap Media component
{ this.state.data.map((d) => {
return(
<Media>
<Media.Left align="top">
<img width={64} height={64} src={d.url} alt="placeholder thumbnail" />
</Media.Left>
<Media.Body>
<Media.Heading>{d.cardHeading}</Media.Heading>
<p>{d.begin}</p>
<p>{d.end}</p>
<p>{d.days}</p>
<p>{d.turnover}</p>
<p>{d.email}</p>
<p>{d.message}</p>
</Media.Body>
</Media>
)
})
}
I know i can iterate over an Array with map. How do i do it in an Object ? Thank you in advance.
Upvotes: 0
Views: 256
Reputation: 4322
With Object.keys
you get an array of the object keys in this case will be ["someGuy", "secondGuy"]
now you can iterate them and get the all objects of your parent object.
You can do this:
render () {
const { data } = this.state
const keys = Object.keys(data)
return keys.map((key) => {
const d = data[key]
return (
<Media>
<Media.Left align="top">
<img width={64} height={64} src={d.url} alt="placeholder thumbnail" />
</Media.Left>
<Media.Body>
<Media.Heading>{d.cardHeading}</Media.Heading>
<p>{d.begin}</p>
<p>{d.end}</p>
<p>{d.days}</p>
<p>{d.turnover}</p>
<p>{d.email}</p>
<p>{d.message}</p>
</Media.Body>
</Media>
)
})
}
Upvotes: 3
Reputation: 54
You can try Object.getOwnPropertyNames(). It returns all keys‘ names of object as array then you can use object[] to get the value.
Upvotes: 0