Search code examples
javascriptarraysobjectnested

Access nested array of objects


im having real trouble to complete an FullStackOpen exersice, it requires to render some data to the page. Give the next code, i have to render the number of Parts that each Course has, and also so reduce the number of Parts/Exersices to render the total of exersices por each Course.

I am not being able to reach the inside of the Parts array of objects

    {
      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,
        },
      ],
    },
  ];``` 

Solution

  • It's not that difficult, for each element of the array:

    • number of parts is currentElement.parts.length
    • number of exercises can be computed using Array.reduce

    const data = [
      {
        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,
          },
        ],
      },
    ];
    
    const res = []
    
    for (const course of data) {
      const tmpObj = {
        courseName: course.name,
        parts: course.parts.length,
        exercises: course.parts.reduce((a,b) => a + b.exercises, 0)
      }
      
      res.push(tmpObj)
    }
    
    console.log(res)