What is the best way to iterate through a JSON file?

Looking at my JSON file:

{
    "stats": {
        "operators": {
            "recruit1": {
                "won": 100,
                "lost": 50,
                "timePlayed": 1000
            },
            "recruit2": {
                "won": 200,
                "lost": 100,
                "timePlayed": 2000
            },
            "recruit3": {
                "won": 50,
                "lost": 10,
                "timePlayed": 500
            }
        },
        "modes": {
            "secure": {
                "won": 80,
                "lost": 40,
                "bestScore": 7582
            },
            "bomb": {
                "won": 12,
                "lost": 18,
                "bestScore": 4500
            }
        }
    }
}

I am trying to present this data in a table format: .

I attempted to use a for-in loop, but only managed to get the names without their corresponding values.

Answer №1

To get started, follow these steps:

let data = {
"stats": {
    "operators": {
        "recruit1": {
            "won": 100,
            "lost": 50,
            "timePlayed": 1000
        },
        "recruit2": {
            "won": 200,
            "lost": 100,
            "timePlayed": 2000
        },
        "recruit3": {
            "won": 50,
            "lost": 10,
            "timePlayed": 500
        }
    },
    "modes": {
        "secure": {
            "won": 80,
            "lost": 40,
            "bestScore": 7582
        },
        "bomb": {
            "won": 12,
            "lost": 18,
            "bestScore": 4500
        }
    }
}
}

for(let key in data.stats){
  console.log('-',key)
  for(let subKey in data.stats[key]){
    console.log('-----',subKey)
    for(let nestedKey in data.stats[key][subKey]){
      console.log('---------',nestedKey +': '+ data.stats[key][subKey][nestedKey]);
    }
  };
}

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

What is the most efficient way to use a for loop with JavaScript querySelectorAll to move multiple images?

I'm trying to move multiple images by defining each one with a for loop. Below is the code I have: var elem = document.querySelectorAll(".yikama"); var el; for (i = 0; i < elem.length; i++) { var el = elem[i] el.addEventListener(& ...

Transferring a row name from PHP to AJAX using jQuery - the complete guide

In my current project, I have a table that displays details fetched from the database. if(mysql_num_rows($sql) > 0) { $row_count_n = 1; while($rows = mysql_fetch_assoc($sql)) { extract($rows); $options1 = select_data_as_options( ...

Persistence of query parameters from old routes to new routes using vue-router

Whenever a query parameter called userId is present in a route within my application, I want the subsequent routes to also include this query parameter. Instead of manually modifying each router-link and router.push, I am looking for a solution using rout ...

Is there a way to integrate the distanceTo function from Leaflet into my own custom library that I am planning to develop?

I am currently incorporating leaflet into my project and I have encountered the distanceTo method which calculates the distance between two coordinates. My goal is to create a separate JS file with a function named getDistance() where I can house the logic ...

Enhancing Vue.js Scripts with Laravel Localization Language-Strings

Within my vue.js script, I have successfully implemented a sweetalert using two Laravel localization language strings. Now, I am attempting to utilize the same language strings as data properties in another vue.js component script. The issue arises when t ...

Showing list data from script to template in vue - A step-by-step guide

My task involves displaying data from the main table in MySQL. I need to show the type of each major by comparing it with the id in the faculty table. I have successfully logged this information using console.log, but I'm unsure how to display it on t ...

Change the position of an HTML image when the window size is adjusted

My web page features a striking design with a white background and a tilted black line cutting across. The main attraction is an image of a red ball that I want to stay perfectly aligned with the line as the window is resized, just like in the provided gif ...

Is there a way to track the number of visits by a 'user' to a website?

Looking to hide certain parts of my website from users who have visited more than a specified number of times. The NY Times site has something similar. Utilizing react & firebase for this project. Considered using IP addresses, but it seems to identify l ...

Having trouble incorporating Duo Web SDK into angular application

We are currently working on incorporating Duo Two-factor authentication into our Angular application. For instructions, you can take a look at the documentation available here. The issue we are encountering is that their JavaScript file searches for an i ...

Deleting a character creates an error

I am conducting a small experiment with a simple goal: to filter and search for users whose names match the current value typed into an input text field. To implement this functionality, I am using RegExp(). Everything works well except when I delete a cha ...

The useReducer function dispatch is being called twice

I can't figure out the reason behind this issue. It seems that when strict mode is enabled in React, the deleteItem function is being executed twice. This results in the deletion of two items instead of just one - one on the first round and another on ...

Creating a dynamic loader with JavaScript and PHP: A step-by-step guide

Currently focused on PHP development, my task involves retrieving data from a database using multiple queries. The database may contain anywhere from 10 records to 10,000 records. I am looking for a way to incorporate a progress bar that displays the com ...

Steps for adding multiple images to a page in a React application:1. Create a

Having trouble displaying images on a React page. I have a directory with 30 images that I want to display on the page (.jsx file). Instead of exporting each image individually, is there a faster way to accomplish this task? Any ideas or suggestions would ...

ES6 does not work with React hello world

Can anyone help me with troubleshooting my code? I've checked the console on jsbin and can't find any errors. http://jsbin.com/susumidode/edit?js,console,output Class secondComponenent extends React.Component { render(){ return ( &l ...

Aligning text vertically to the top with material UI and the TextField component

Seeking guidance on adjusting vertical alignment of text in <TextField /> const styles = theme => ({ height: { height: '20rem', }, }); class Foo extends React.component { ... <TextField InputProps={{ classes: ...

What is preventing my function from retrieving data from the JSON File?

Exploring the realm of JSON file manipulation, I am delving into how it functions. Equipped with a JSON file attached to my document and a function sharing the same name as my object in the JSON file. However, despite all efforts, the data is not being dis ...

The functionality of the Sticky state is not effective when it is implemented on a state that contains parameters

It appears that the sticky state feature does not function properly when there are parameters involved. For example: $stateProvider .state('store', { url: '/store', abstract: true, onEnter: ...

The functionality of the Bootstrap dropdown list button is not functioning properly on mobile devices

Currently, I am in the process of developing a website and testing its mobile view on my iPhone. The website is still using bootstrap 3, but I have encountered some issues. When I tap on the navigation button on my iPhone, nothing happens - no dropdown lis ...

Trouble with getting started on the Google Sheets API (v4) tutorial

I'm currently working my way through a tutorial that can be found at the link below: https://developers.google.com/sheets/api/quickstart/nodejs# When I reach the step of running the quick start file (node quickstart.js), I encounter the following err ...

I've encountered a peculiar error that is new to me while using bootstrap and javascript. Can anyone shed light on what this error signifies?

Hey there! I've come across this error in the console while attempting to utilize Bootstrap. It seems that a style is being refused from 'http://127.0.0.1:5500/node_modules/font-awesome/css/font-awesome.min.css' due to its MIME type ('t ...