0

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.

2 Answers 2

2

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>
          )))
      ))}
)

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, it worked, but partially. Actually inner1 & inner2 both have different type (or name) of items. eg: your answer is returning a total of 6 elements, while inner1 has 2 elements and inner2 has 1 element in it. I updated my question to make it more understandable.
1

It depends on what you need, but I think here's what you are looking for:


return(
{
  outer.map(({ inner1, inner2 }) => {
    
    let a = inner1.map(({ data }) => (
        // do something
    ));

    let b = inner2.map(({ data }) => (
        // do something
    ));

   return something here

  })
}
)

3 Comments

didn't help! I updated my question to make it more understandable.
can you also show what's the final result you want to be rendered? still not clear what you are asking for.
I just want to get (say print) whatsoever is therein (a, b, c, d) that's it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.