I want to Map following state:
const initialState = {
outer: [
{
inner1: [
{ a: 'aaa' },
{ b: 'bbb'}
......
],
inner2: [
{ c: 'ccc' },
{ d: 'ccc'}
......
]
},
{
inner1: [
{ a: '111' },
{ b: '222'}
......
],
inner2: [
{ c: '333' },
{ d: '444'}
......
]
},
......
]
}
And here, what I tried so far:
render() {
return (
{
outer.map(({ inner1, inner2 }) => (
inner1.map(({ a, b }) => (
// do something
<p> { a }</p>
<p> { b }</p>
)),
inner2.map(({ c, d }) => (
// do something
<p> { c }</p>
<p> { d }</p>
))
))
}
)
}
But the above solution is mapping data of one inner state (inner2
) only.
So, how can I render such a structure using map? Suggest any other better approach as well if any.
You are using comma operator which ignores the first expression and returns latter one.
Use Array.prototype.concat
method to merge two arrays.
return(
{
outer.map(({ inner1, inner2 }) => (
inner1.map(({ a, b }) => (
// do something
<p> { a }</p>
<p> { b }</p>
)).concat(inner2.map(({ c, d }) => (
// do something
<p> { c }</p>
<p> { d }</p>
)))
))}
)