Exploring nested keys within JSON data using TypeScript

I am currently working with this object structure

{
    "Monday": [
        {
            "morning": [
                {
                    "start_time": "02:00",
                    "end_time": "07:30"
                }
            ],
            "afternoon": [
                {
                    "start_time": "02:00",
                    "end_time": "05:00"
                }
            ],
            "evening": [
                {
                    "start_time": "02:30",
                    "end_time": "07:00"
                }
            ]
        }
    ],
    "Tuesday": [
        {
            "morning": [
                {
                    "start_time": "02:00",
                    "end_time": "07:30"
                }
            ],
            "afternoon": [
                {
                    "start_time": "02:00",
                    "end_time": "05:00"
                }
            ],
            "evening": [
                {
                    "start_time": "02:30",
                    "end_time": "07:00"
                }
            ]
        }
    ],
..
}

I am trying to iterate through all the keys and values of this object

for (var prop in this.jsonData) {
  console.log("Key:" + prop);
  console.log("Value:" + this.jsonData[prop]);
}

However, I am currently facing an issue

Key:Monday value : undefined

I am looking to access the inner object values instead.

Answer №1

To access the inner object values, looping through the inner arrays is necessary. This can be achieved by:

  • Object.entries() to obtain an array of key-value pairs for the outer and inner objects.
  • Iterating through the arrays,
  • and destructuring to extract the values directly from the objects.
Object.entries(this.jsonData).forEach(([day, dayData]) => {
  console.log("Day:", day);
  const timePeriods = dayData[0];

  Object.entries(timePeriods).forEach(([timePeriod, slots]) => {
    console.log("  Time Period:", timePeriod);

    slots.forEach(({ start_time, end_time }, i) => {
      console.log(`    Slot ${i + 1}`);
      console.log("      Start Time:", start_time);
      console.log("      End Time:", end_time);
    });
  });
});

const jsonData = {
  Monday: [
    {
      morning: [
        {
          start_time: "02:00",
          end_time: "07:30",
        },
      ],
      afternoon: [
        {
          start_time: "02:00",
          end_time: "05:00",
        },
      ],
      evening: [
        {
          start_time: "02:30",
          end_time: "07:00",
        },
      ],
    },
  ],
  Tuesday: [
    {
      morning: [
        {
          start_time: "02:00",
          end_time: "07:30",
        },
      ],
      afternoon: [
        {
          start_time: "02:00",
          end_time: "05:00",
        },
      ],
      evening: [
        {
          start_time: "02:30",
          end_time: "07:00",
        },
      ],
    },
  ],
};

Object.entries(jsonData).forEach(([day, dayData]) => {
  console.log("Day:", day);
  const timePeriods = dayData[0];

  Object.entries(timePeriods).forEach(([timePeriod, slots]) => {
    console.log("  Time Period:", timePeriod);

    slots.forEach(({ start_time, end_time }, i) => {
      console.log(`    Slot ${i + 1}`);
      console.log("      Start Time:", start_time);
      console.log("      End Time:", end_time);
    });
  });
});


Edit:

It is necessary to explicitly typecast the slots. For example:

(slots as { start_time: string; end_time: string }[]).foreach(...)

Typescript playground

Answer №2

Exploring Nested Objects

The complexity of the object structure requires us to navigate deep within each subobject, such as the hierarchy of days and times.

To achieve this, a function can be created:

this.jsonData = {
    "Monday": [
        {
            "morning": [
                {
                    "start_time": "02:00",
                    "end_time": "07:30"
                }
            ],
            "afternoon": [
                {
                    "start_time": "02:00",
                    "end_time": "05:00"
                }
            ],
            "evening": [
                {
                    "start_time": "02:30",
                    "end_time": "07:00"
                }
            ]
        }
    ],
    "Tuesday": [
        {
            "morning": [
                {
                    "start_time": "02:00",
                    "end_time": "07:30"
                }
            ],
            "afternoon": [
                {
                    "start_time": "02:00",
                    "end_time": "05:00"
                }
            ],
            "evening": [
                {
                    "start_time": "02:30",
                    "end_time": "07:00"
                }
            ]
        }
    ],
}


for (var day in this.jsonData) {
  console.log("Day:" + day);
  
  // Accessing the array of schedules for the current day
  var schedules = this.jsonData[day];
  
  // Looping through the array of schedules
  for (var i = 0; i < schedules.length; i++) {
    var schedule = schedules[i];
    
    // Looping through the keys (morning, afternoon, evening)
    for (var timeOfDay in schedule) {
      console.log("Time of day: " + timeOfDay);
      
      // Accessing the array of time slots for the current time of day
      var timeSlots = schedule[timeOfDay];
      
      // Looping through the array of time slots
      for (var j = 0; j < timeSlots.length; j++) {
        var timeSlot = timeSlots[j];
        
        console.log("Start time: " + timeSlot.start_time);
        console.log("End time: " + timeSlot.end_time);
      }
    }
  }
}

Note: Instead of simply logging the data, a search key can be implemented to find specific days or times, and these values can also be stored for future use.

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

Unable to get the Express.js Router functioning correctly on my server, even in a basic scenario

I am encountering an issue with using express.Router(). It was not functioning correctly in my application for serving JSON from MongoDB, so I attempted to simplify the scenario. However, I am receiving a 404 Not Found error in the request. What steps shou ...

What is the best way to incorporate the keydown event into an if/else statement?

For my middle school science fair project, I am working on creating an online light bulb that features a hidden surprise, or an "easter egg," that triggers an alert when activated by a specific key press. Below is the current code I have developed: HTML & ...

Having difficulty entering text into a "Search Input Field" that is a react component in testcafe

Struggling to input text in a "Type to search dropdown" that is a react component. While able to click on the component, typing any text seems to be an issue. Listed below is an example of the code: import { Selector } from 'testcafe'; test(&ap ...

I need to access a directory that is outside of my current folder in Express.js

I have two folders within my main folder; one is for front-end and the other is for back-end. project ├── back-end │ ├── public │ └── routes │ ├── Calling.js │ └── index.js └── front-end ├ ...

How do you create an AngularJS directive with HTML content?

I am currently working on a directive that aims to load a webpage, make it accessible in a service, and also have its content available in the scope within the directive's element. Here is a simplified explanation of what I am trying to achieve: < ...

Using TypeScript to narrow down types within mapped types

Can you create a mapped type based on the property type? For example, if I want to map all properties with type String to Foo and all other types to Bar. Can this be done like this: type MappedType<T> = { [P in keyof T]: T[P] === String ? Foo : B ...

Border becomes dashed when dragging and dropping

I am working on enabling drag and drop functionality for users. When an item is lifted from its original position, a gray dashed box should appear in its place. As the item is moved closer to another spot, the containers adjust to create a target area (gra ...

Substitute all instances of <table> with <div> tags, making sure to include specifications for

Currently, I find myself immersed in a project that relies heavily on tables, which isn't exactly ideal but is what the marketing department insists upon... To tackle this issue, I have implemented jQuery to convert all tables into DIVs, and so far, ...

Querying for the presence of an ObjectId in an array in Mongoose

I'm developing a Node.js project that involves two models: User and Project. Below is the Schema for the Project model: const ProjectSchema = new mongoose.Schema({ name: { type: String, maxlength: 50, required: true, } ...

Utilizing JQuery to extract information from the Bing Search API in JSON format

Having some trouble parsing the JSON from Bing Search API Version 7 with this code. I'm specifically looking to extract "name" and "url" fields. Here's my current code: You can find the Bing JSON Results here. let query = escape($('#book&ap ...

Tracking form submissions on Internet Explorer using a bootstrap modal window - a step-by-step guide

Currently, I have a form that users fill out and submit using jquery with $("form").submit(); During the submission process, I utilize a modal window from the Twitter Bootstrap library to block the screen and inform the user that the form is being process ...

Resetting the state of toggle/click states in AJAX and jQuery

Currently, I am encountering a small dilemma with a .on function and AJAX in conjunction with a mobile menu. The mobile menu is located in the header of a site that relies heavily on AJAX for its content loading. This poses an issue because when an AJAX ca ...

Utilize AngularJS ng-repeat directive to refine JSON objects

I'm working on an angular js controller with a json array that organizes countries by continents. Each continent consists of its own array of countries. //CONTROLLER app.controller('CountryController', function(){ this.continents = ...

Refreshing the page causes JavaScript to fail loading

Recently, I encountered a puzzling error. Upon visiting this link The carousel fails to load properly near the bottom of the page. However, if you click on the logo or navigate back to the home page, it works fine. Additionally, performing a command + r ...

struggling to transfer information from JavaScript to Jade within the Node.js environment

Currently, I am retrieving a row from a Cassandra table called "emp". My objective is to pass the data retrieved from the JavaScript file to a Jade file in order to display this information on the user interface. In my JavaScript function: router.get(&a ...

Experiencing issues with creating HTML using JavaScript?

I'm a JavaScript novice and struggling to figure out what's wrong with my code. Here is the snippet: var postCount = 0; function generatePost(title, time, text) { var div = document.createElement("div"); div.className = "content"; d ...

Angular component name constraints - 'the selector [your component name] is not permissible'

When trying to generate a component using the Angular 6 CLI (version 6.0.7), I encountered an issue. After typing in ng g c t1-2-3-user, I received an error message stating that the selector (app-t1-2-3-user) is invalid. I wondered if there was something ...

Warning from Cytoscape.js: "The use of `label` for setting the width of a node is no longer supported. Please update your style settings for the node width." This message appears when attempting to create

I'm currently utilizing Cytoscape.js for rendering a dagre layout graph. When it comes to styling the node, I am using the property width: label in the code snippet below: const cy = cytoscape({ container: document.getElementById('cyGraph&apo ...

Utilize JavaScript to communicate with the backend server

I'm embarking on my first Cordova application, utilizing HTML, CSS, and JavaScript. My current objective is to trigger a local server call upon button click, with the intention of logging something to confirm functionality. However, I'm encounter ...

Typescript and MomentJS integration - What is the data type of the moment() function?

Currently in the process of upgrading my project from ES5 to ES6, I've encountered a problem with MomentJS (version 2.18.1). The issue arises when dealing with variables that are Moment objects and the inability to call moment() on them. For instance ...