The variable that is extracted from a JSON object within an array successfully logs to the console inside a loop. However, when attempting to use the same variable for summation

I have a looping task where I need to add the values of certain objects together in an array. While I can successfully log the values individually, like this:

console.log(workouts[0].exercises[0].break);

When I try to incorporate them into a loop, I encounter an error message on the console:

Uncaught TypeError: Cannot read property 'duration' of undefined

If I place the line targeting "break" first, it tells me it cannot read property 'break' of undefined, suggesting that "exercises" may not be defined correctly. However, I am able to log its values without any issues.

How can I ensure that I am able to log the correct value even when it might not be definable? Below is my code snippet:

var workouts = {
  "workouts":
  [
    {
      "title": "Full Body",
      "exercises":
      [
        {
          "name": "Push Ups",
          "duration": 30,
          "break": 10
        },
        {
          "name": "Squats",
          "duration": 30,
          "break": 10
        },
        {
          "name": "Running in Place",
          "duration": 30,
          "break": 10
        }
      ]
    }
  ]
};

for (var i = 0; i < workouts.length; i++)
{
  for (var k = 0; k != workouts.length; k++)
  var durations = workouts[i].exercises[k].duration;
  var breaks = workouts[i].exercises[k].break;
  var totalTime = durations + durations;
  console.log(totalTime);
}

Answer №1

Attempt using

workouts["workouts"][i].exercises[k].break
. Avoid utilizing the same i from the workout object to iterate through exercises. Determine the length with exercises.length and initiate a new loop based on that count.

Answer №2

let exerciseList = {
  "exercises":
  [
    {
      "title": "Strength Training",
      "activities":
      [
        {
          "name": "Bench Press",
          "duration": 45,
          "rest": 15
        },
        {
          "name": "Deadlifts",
          "duration": 45,
          "rest": 15
        }
      ]
    }
  ]
};
console.log(exerciseList.exercises[0].activities.length);
for (let j = 0; j < exerciseList.exercises[0].activities.length; j++)
{
  console.log(exerciseList.exercises[0].activities[j].rest); 
  let activityDuration = exerciseList.exercises[0].activities[j].duration;
  let restTime = exerciseList.exercises[0].activities[j].rest;
  let totalTimeSpent = activityDuration + restTime;
  console.log(totalTimeSpent);
}

Answer №3

Your problem lies in the syntax you used.

var intervals = workouts[i].excercises[i].interval;

It should actually be

var intervals = workouts[i].exercises[i].interval;

Also, consider implementing nested loops as recommended by others for iterating through the exercises array.

Answer №4

It seems that additional data from the JSON is required for a better understanding:

In order to access objects within the workouts["workouts"] array, it is necessary to specify the key rather than just the array index [n]. This can also be written as workouts.workouts[n].exercises[n].

var workouts = {
  "workouts": [{
    "title": "Full Body",
    "exercises": [{
      "name": "Push Ups",
      "duration": 30,
      "break": 10
    }, {
      "name": "Squats",
      "duration": 30,
      "break": 10
    }, {
      "name": "Running in Place",
      "duration": 30,
      "break": 10
    }]
  }, {
    "title": "Lower Body",
    "exercises": [{
      "name": "Squats",
      "duration": 30,
      "break": 10
    }, {
      "name": "Running in Place",
      "duration": 30,
      "break": 10
    }]
  }]
};

var totalTime = 0;
for (var i = 0; i < workouts["workouts"].length; i++) {
  for (var j = 0; j < workouts["workouts"][i].exercises.length; j++) {
    var durations = workouts["workouts"][i].exercises[j].duration;
    var breaks = workouts["workouts"][i].exercises[j].break;
    totalTime = totalTime + durations + breaks;
    console.log(workouts.workouts[i].title + " (" + workouts.workouts[i].exercises[j].name + "): " + (durations+breaks) + " \n ");
  }
}
console.log("total: " +totalTime);

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

Is it possible to execute a function defined within an eval() function using setInterval()?

const evaluation = eval(document.getElementById("codearea").value); setInterval(evaluation, 10); I am seeking a way to access a function that is declared within the eval function, for example: setInterval(evaluation.examplefunc, 10) I attempted ...

Sorting and Displaying Partial Data from Firebase in JavaScript

I have been working on a function to sort data from Firebase by the highest score value and display only the top 5 scores. However, I am facing an issue where all the data is appearing in order, which isn't very helpful for me. The gotData function p ...

What is the most efficient method to refresh $scope following data retrieval from a service in AngularJS?

In my current project using angularJS, I have encountered a challenge while working with an API service to fetch and display data in different parts of the app under various controllers. Initially, everything ran smoothly until I centralized the API calls ...

Utilizing the dynamic flair with React's map functionality

In my display area, which is a div element, I have rendered some text using spans. I utilized the map function to render the text from an array. The issue arises when I apply a color class to the span elements within the map function, causing all text to ...

"Emphasize menu items with an underline as you navigate through the

I am using Gatsby with React and have a navigation menu with links. I would like to make it so that when a link is clicked, a border bottom appears to indicate the current page, rather than only on hover. <ul className="men" id="menu"> ...

Show the date broken down into day, month, and year, as well as various combinations thereof

My goal is to display the current month, year, month-year, and day-month in my HTML page. Here is the JavaScript code I am using: var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", ...

Assistance with designing in JavaScript and Python

Currently, I have a setup where my external website is extracting data from an iframe within our internal company intranet using Javascript. The extraction process is successful, but now I am faced with the challenge of accessing this harvested data in ord ...

Utilize Javascript to pull information from a REST API and generate a dynamic table with the retrieved

Generating a table from JSON data obtained from a REST API without utilizing Angular poses a challenge in a specific application. My query is: Is it necessary to use var table = document.createElement("TABLE"); within the script to construct the entire ta ...

Leveraging Vue.js as a development dependency in a TypeScript project

I am currently working on a .net core project where all client-side scripts are written in TypeScript. I have a desire to incorporate Vue.js into the TypeScript codebase. Below are snippets of the necessary configurations: tsconfig.json { "compilerOpti ...

Extracting data types from strings in JavaScript

I have been developing a project using HTML and JavaScript where I need to extract two strings from the HTML script, pass them to JavaScript, and convert them into their respective variable types similar to using typeof. For instance, "true" shou ...

Trapped in the JavaScript Checkbox Filter Maze

After successfully creating a javascript-only filter, I have hit a roadblock and could really use some assistance. The filter is divided into "days" and "events". When a user clicks on a day or multiple days, the events for those selected days are displa ...

The "useFindAndModify" option is not compatible

I am facing an issue connecting to my database using mongoose, and the console displays 'option usefindandmodify is not supported'. I am currently using mongoose version 6.0.0 Here is my code: mongoose.connect(constants.CONNECTION_URL, { ...

Debugging a node.js application remotely using SAP Cloud Foundry

Having successfully deployed multiple node.js express services on SAP Cloud Foundry, we have encountered a roadblock in the form of remote debugging. Recognizing that others may be facing similar challenges, we are putting forth a direct inquiry: What is ...

What is the best method for accessing a value in IndexedDB while utilizing service workers?

I am feeling overwhelmed by the concepts of IndexedDB and serviceworkers as I try to transform them into a functional application. Despite my extensive research, including studying various examples, I am struggling to integrate the two technologies effecti ...

The shared hosting environment encountered an error during the Next JS build process

When I execute the command "npm run build" on my shared hosting server, it throws an error message: spawn ENOMEM. Interestingly, this command runs perfectly fine on my localhost and has been running smoothly on the hosting server for a few weeks until yest ...

What are some ways I can receive a response promptly from a service in AngularJS?

After calling the service method from the controller, there is a delay in receiving the data that I need to populate a dropdown. My expectation is that when I call this method from the controller, it should return a response immediately, and then other log ...

Problem with pairing table rows and cells, slight misalignment of 1 pixel

In my attempt to align an icon and text side by side, with the icon on the left and the text on the right, I encountered an issue where the element's box seems to be consistently 1 pixel off. This misalignment is causing the text to not line up proper ...

Utilizing ReactRouter via CDN without needing npm

As someone new to React, I have been practicing by directly incorporating the react.js and react-dom.js files along with browser.min.js for JavaScript transformation into my HTML page. Now, I am looking to utilize react-router and have added the ReactRoute ...

Issue with jQuery clone(): original content's radio button toggling display function not functioning as intended

I'm duplicating HTML code using jQuery and adding it to a div. However, after appending the original content, both radio buttons become unchecked. How can I resolve this issue? Can anyone assist me with this? jsfiddle HTML <div class="conten ...

Transmit a data element from the user interface to the server side without relying on the

I have developed a MEAN stack application. The backend of the application includes a file named api.js: var express = require('express') var router = express.Router(); var body = 'response.send("hello fixed")'; var F = new Function (" ...