Exploring the depths of nested object arrays

I'm really struggling to complete a FullStackOpen exercise that requires rendering data to the page. With the following code, I need to display the number of Parts each Course has and also reduce the number of Exercises/Parts to show the total exercises for each Course.

I'm having difficulty accessing 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,
        },
      ],
    },
  ];

Answer №1

Breaking it down is not that challenging, here's the process for each individual element within the array:

  • The quantity of parts can be determined by accessing currentElement.parts.length
  • The total number of exercises can be calculated utilizing the Array.reduce method

const data = [
  {
    name: "Full Stack web development course",
    id: 1,
    parts: [{
        name: "JavaScript Basics",
        exercises: 15,
        id: 1,
      },
      {
        name: "Using Express middleware",
        exercises: 8,
        id: 2,
      },
      {
        name: "Backend with MongoDB",
        exercises: 12,
        id: 3,
      },
    ],
  },
  {
    name: "React Framework",
    id: 2,
    parts: [{
        name: "State management in React",
        exercises: 6,
        id: 1,
      },
      {
        name: "Hooks and effects",
        exercises: 9,
        id: 2,
      },
    ],
  },
];

const result = []

for (const program of data) {
  const tempObject = {
    programName: program.name,
    parts: program.parts.length,
    exercises: program.parts.reduce((a,b) => a + b.exercises, 0)
  }
  
  result.push(tempObject)
}

console.log(result)

Answer №2

If you wish to determine the total number of exercises for each course, you will first need to iterate through each course by name; then, for each list of parts, calculate the total exercise count.

const main = () => {
  const courseData = courses.map(({ name, parts }) => ({
    name,
    parts: parts.length,
    exercises: parts.reduce((sum, { exercises }) => sum + exercises, 0)
  }));
  
  console.log(courseData);
};

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

main();
.as-console-wrapper { top: 0; max-height: 100% !important; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is useEffect being executed twice?

For some reason, when I try to run useEffect for the first time page load, it ends up running twice. I can't seem to figure out why this is happening. Can someone please provide assistance? I'm currently using React 18 and I need help understand ...

Translating from JavaScript to Objective-C using JSON

Can someone help me figure out how to correctly 'return' this JSON object in JavaScript? function getJSONData() { var points = '{\"points\": ['; var params = polyline.getLatLngs(); ...

Selenium and Python encountered an ElementNotInteractableException, indicating that the element was not interactable when inserting a value

My current challenge involves inserting a value into a text box on a web page. The issue I'm facing is that the text box is located at the bottom of the page and seems to be unlocatable by the code initially. Upon inspecting it twice in Chrome, I real ...

Troubleshooting issue with node.js 13 import functionality

$ node --version v13.8.0 We will now proceed to create three files: // package.json { "type": "module" } // foobar.js function foo() { console.log('foo') } export default {foo} // index.js import Foo from './foobar ...

[entity: undefined prototype] { type: 'clip', info: 'Watch my latest video!!' } using nodejs - multer

import routes from "./routes"; import multer from "multer"; const multerVideo = multer({ dest: "videos/" }); export const localsMiddleware = (req, res, next) => { res.locals.siteName = "Webtube"; res.locals.routes = routes; res.locals.user = { isA ...

Tips on displaying hyperlinks within a text area in an Angular application

In my Angular application, I am facing an issue with displaying hyperlinks within a text area box for dynamic content. The hyperlinks are not recognized and therefore cannot be clicked. Can someone please advise on how to properly display hyperlinks with ...

Nested Add and Remove using Jquery

I'm looking for assistance with implementing add/remove functionality for both top-level and sublists, which should result in a serialized output. Can anyone provide guidance on how to achieve this? For example: Add Question Question 1 | Delete An ...

Locate all posts associated with the specified User ID

Using mongoose, I am able to populate the "Post Schema" with relevant information about users who create the posts. postModule.js const mongoose = require('mongoose'); const postSchema = mongoose.Schema({ title:String, description:String, date ...

When using react-router-dom, a blank page may appear for routes that contain more than one path segment followed by a single forward slash "/"

Whenever I attempt to set up a route with more than one "/" (e.g. "/testing/test"), React simply displays a blank page instead of showing the Test component along with the navigation bar and footer. Interestingly, the route "/testi ...

Ways to display map results in multiple columns utilizing react

I am facing a challenge and seeking guidance on how to achieve a specific layout using React. My goal is to display results in two columns as shown below: item 1 | item 4 item 2 | item 5 item 3 | item 6 I have attempted to check the array length and dete ...

Tips for displaying a div near the cursor's location when hovering in React JS

Looking for a way to show a hidden div at cursor position when hovering on Text item1 or item2. Check out the sample GIF animation in this Link My attempt using Jquery code inside React resulted in an error: $(".text-item").mouseenter(function ( ...

Sending both the minimum and maximum slider values to PHP using POST can be achieved by formatting the data correctly

I am attempting to transmit the minimum and maximum values to PHP using submit through a dual slider bar The static page makes a request to the server-side PHP code <?php include('server/server.php') ?> Below is the JavaScript code ...

Creating a file solely for route definitions and then employing them within index.js

My index.js file contains the following routes: import { createRouter, createWebHistory } from '@ionic/vue-router'; import { RouteRecordRaw } from 'vue-router'; const routes = [{ path: '', redirect ...

Utilizing Ajax to upload various files from separate input sources simultaneously

I want to upload multiple textual/select inputs along with two different file inputs to a PHP file using Ajax. The images from the file inputs are specific and need to be identified by their input names, so I cannot use <input type="file" multiple>. ...

Tips for shifting a fabricjs element generated within a nextjs useState hook?

I encountered an issue where creating a fabric canvas in a useEffect() function prevents me from moving the added images. However, if I create the canvas elsewhere (even though it may be subject to useState asynchrony issues), I am able to move the image ...

Master the art of navigating the Windows Sound Recorder with the power of JavaScript

I am creating a project that involves controlling the Windows sound recorder for tasks such as starting, stopping, and saving recordings. Is there a way to do this without displaying the recorder window? I would appreciate any assistance in solving this. ...

Issue: Utilized more hooks than in the previous render cycle

After the initial load of a component that renders and makes data calls on the client side, everything works fine. However, when clicking a "see more" button to make another call, an error occurs in the console indicating that there are too many hooks be ...

I need to change a website into a string so that I can analyze it with javascript. How can I do this?

Currently, I am in the process of creating a website for my video game servers. The admin tool we use outputs the current server status in a .json format as a large text string to this specific URL: My goal is to retrieve the entire text string from the p ...

Conditional styling in React class components depending on the props provided

Dealing with older versions of material-ui that cannot be updated. I'm attempting to modify the background of the Paper component based on various prop combinations without relying on the makeStyles HOC. Is this achievable? The issue seems to lie in ...

What might prevent an onSubmit event from triggering the execution of "checkTheForm()"?

Despite consuming a substantial amount of information on the internet, I still find myself puzzled by why my code isn't functioning as expected. I acknowledge that there are numerous tutorials out there guiding me to use <form action="index.html" o ...