Search code examples
javascriptreactjsecmascript-6es6-map

How can I map a 2 different arrays with the same component values?


const App = () => { 
  const courses = [
    {
      name: 'Half Stack application development',
      id: 1,
      parts: [
        {
          name: 'Fundamentals of React',
          exercises: 10,
          id: 1
        },
        {
          name: 'Using props to pass data',
          exercises: 7,
          id: 2
        },
        {
          name: 'State of a component',
          exercises: 14,
          id: 3
        },
        {
          name: 'Redux',
          exercises: 11,
          id: 4
        }
      ]
    }, 
    {
      name: 'Node.js',
      id: 2,
      parts: [
        {
          name: 'Routing',
          exercises: 3,
          id: 1
        },
        {
          name: 'Middlewares',
          exercises: 7,
          id: 2
        }
      ]
    }
  ]

I am trying to access and print the second array in the content courses.parts.names. I was successful to access the first array by using a snipet below.

courses.map( course => <h2 key = {course.id}> {course.name} <h2/>

But I have difficulty figuring out how to access the second sub-child array.

Thank you.


Solution

  • The steps needed would be:

    1. Reduce the courses array into an array of the parts

    2. Iterate over the new parts array to render the components

    const courses = [ ... ];
    // Step 1
    const parts = courses.reduce((parts, course) => {
        return [...parts, ...course.parts];
    }, []);
    
    // Step 2
    parts.map(part => <h2 key={part.id}>{part.name}<h2/>);