Looping through JSON data in Java Script is a common task for

How can I extract and store all grades from the provided JSON data for every year into an array? I am new to JavaScript, so any explanation would be helpful. The expected array based on this example should be [2,4,2,5,4,5,4.5,2,3.5,5,5,5,5,5]

{
    "first_name": "Ala",
    "last_name": "Kowalski",
    "birth_date": "29 AUG 1990",
    "indeks_number": "9454530",
    "year_of_study": "2",
    "courses": {
        "2013": {
            "AlgorithmsI": {
                "grades": {
                    "exercices": [
                        2,
                        4
                    ],
                    "lecture": [
                        2,
                        5
                    ]
                }
            },
            "BasicPhysicsI": {
                "grades": {
                    "exercices": [
                        4
                    ],
                    "lecture": [
                        5
                    ]
                }
            },
            "ProgrammingI": {
                "grades": {
                    "exercices": [
                        4.5
                    ],
                    "lecture": [
                        2,
                        3.5
                    ]
                }
            }
        },
        "2014": {
            "ProgrammingII": {
                "grades": {
                    "exercices": [
                        5
                    ],
                    "lecture": [
                        5
                    ]
                }
            },
            "BasicPhysicsII": {
                "grades": {
                    "exercices": [
                        5
                    ],
                    "lecture": [
                        5
                    ]
                }
            },
            "AlgorithmsII": {
                "grades": {
                    "exercices": [
                        5
                    ],
                    "lecture": [
                        5
                    ]
                }
            }
        }
    }
}

Answer №1

One method I may consider using is utilizing JSON.stringify to loop through the object:

gradesList = [];
JSON.stringify(obj, function(key, value) {
    if (key === 'grades') 
        gradesList = gradesList.concat(value.exercises, value.lecture);
    return value;
});

Explanation of the Process

The purpose of JSON.stringify is to convert an object into a JSON string format. During this process, it traverses through all values within the object at every level. Additionally, it allows for a replacer parameter, which is a function that analyzes each key/value pair encountered. In this situation, the replacer function is utilized not for controlling the conversion into a string but rather to inspect each key/value pair to determine if the key corresponds to 'grades'. If so, the respective grades are appended to the gradesList array. It is important to return value so that the iteration by JSON.stringify continues. The actual result produced by JSON.stringify is disregarded and discarded.

Answer №2

Hey, here's a code snippet you can give a shot.

function getGrades(jsonData) {
    var gradesList = [];
    
    for (var year in jsonData.courses) {
        for (var lesson in jsonData.courses[year]) {
            for (var exerciseGrade in jsonData.courses[year][lesson].grades.exercises) {
                gradesList.push(jsonData.courses[year][lesson].grades.exercises[exerciseGrade]);
            }
            
            for (var lectureGrade in jsonData.courses[year][lesson].grades.lecture) {
                gradesList.push(jsonData.courses[year][lesson].grades.lecture[lectureGrade]);
            }
        }
    }
    
    return gradesList;
}

Answer №3

let newGrades = [];
let dataObject = <your Object>;

analyzeObj(dataObject);

function analyzeObj(data) {
    for (let key in data) {
        if (key=='exercices' || key=='lectures') {
            for (let i=0;i<data[key].length;i++) {
                newGrades.push(data[key][i]);
            }
        } else {
            analyzeObj(data[key]);
        }
     }
}

Answer №4

Repetitive:

function each(list, func) {
    Object.keys(list).forEach(function (key) {
        var item = list[key];
        func(item, key);
    });
}

function inArray(arr, element) {
    return arr.indexOf(element) > -1;
}

function isSimpleObject(obj) {
    return !!obj && typeof obj === 'object' && obj.constructor === Object;
}

function getValues(data) {
    var values = [];
    each(data, function (item, key) {
        if (inArray(['workouts', 'reading'], key)) {
            values = values.concat(item);
        } else if (isSimpleObject(item)) {
            values = values.concat(getValues(item));
        }
    });
    return values;
}

You can try this out in Node.js by using:

var assert = require('assert');
assert.deepEqual(getValues(sampleData),
                 [2, 4, 2, 5, 4, 5, 4.5, 2, 3.5, 5, 5, 5, 5, 5, 5]);

Replace sampleData with your own JSON information.

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

In the Kendo AngularJS tree view, prevent the default behavior of allowing parent nodes to be checked

Hi there, I am currently using Kendo treeview with Angularjs. My tree view has checkboxes in a hierarchy as shown below Parent1 Child1 Child2 I would like the functionality to work as follows: Scenario 1: if a user selects Parent1 -> Child1, Chil ...

`switch tabs visibility based on checkbox selection`

There are 4 tabs available on a JSP page: Tab 1, Tab2, Tab3, and Tab4. Initially, only Tab1 is enabled, allowing users to freely work within that tab. However, Tabs 2, 3, and 4 are disabled, preventing users from accessing their contents. A checkbox is lo ...

Struggling with parsing JSON strings into PHP arrays

I'm looking to transmit a JSON string using JavaScript and later convert it into an array using a PHP encoding function. After successfully converting the string in JavaScript and transmitting it via Ajax to a PHP page, I am encountering difficulties ...

Implement a time interval in a recurring jQuery / Ajax operation

I'm attempting to introduce a delay into a repeating query. After some research, I've discovered that .delay isn't the right approach. Instead, it's recommended to use either setInterval or setTimeout. However, my attempts with both me ...

Ways to prevent endless loops from occurring?

Here is the code for my component: const Inscriptions = () => { // getting state const { inscriptions, loading } = useSelector( state => state.user ); // flag const instances = Object.keys(inscriptions).length; // dispatch ...

Discover the power of Snowflake's lateral flatten function in exploding multiple JSON values within nested JSON lists!

I have a variant table containing 24 JSONs that look like the following (one per row): { "context": "marketplace", "metadata": { "app_version": "1.0.4 (166)", }, "params": { " ...

Ensuring validity using dynamic context objects within Joi

I need to implement a dynamic validation system that involves downloading an object at runtime and saving it as a well-formed .json file. The objective is to use the values from this downloaded object as part of a validation process using Joi.validate wi ...

What is the best way to convert this JSON string into a JSON object?

I am facing an issue with extracting a JSON document from the "body" field of a message sent to a Gateway endpoint through an SNS HTTPs subscription. The JSON document is being properly mangled with escape characters and new lines, causing json.loads() in ...

Unable to capture HTML form input in $_POST[]

I've encountered an unusual issue while transferring data from an email form (HTML5) to ajax/JSON and receiving false in order to prevent redirection to the php script after pressing the submit button. When I include commas between each data paramete ...

What are the steps for releasing a Next.js app as an npm package?

Currently, my web application is developed using Next.js. I am interested in distributing it as an npm package for others to utilize in their projects. Despite my efforts to search and seek assistance through Google, I have not come across any valuable ins ...

The TypeScript error "File 'XXX' is not recognized as a module" is preventing successful compilation

Is there a way to import a module from an external file into another TS file? Even after following the steps, when I tried to do so in VSCode, it gave me an error saying that the file 'XXX' is not a module: Here's the error I encountered I ...

The dropdown feature is malfunctioning. (Using Angular 8 and Bootstrap)

I'm encountering an issue with displaying a dropdown and its options using the bootstrap directive 'ngbDropdown'. When I follow this example from the documentation: <div ngbDropdown class="d-inline-block"> <button class="btn ...

Using NiFi - Easy steps to send a GET request with JSON using the InvokeHTTP processor

I am attempting to send a GET request with JSON data to https://www.example.com/api/ GET /path/to/data { "abcd": [ "a1", "a2" ] } The URL encoding for this request is as follows: https://www.example.com/api/path/to/data?json=%8B%0B%+..... I ha ...

What is the reason behind the response entity returning the JSON with the setter and getter names instead of the data member names?

Upon examining the code below, I noticed that when returned by the Spring ResponseEntity, I am receiving a JSON object with the setter name instead of the data member name. However, if I change setData to setResult and getData to getResult, the response ch ...

iOS [__NSCFString > retrieving value with keyed subscript:]

I've been working on integrating a tableview with a Twitter feed into my iOS app. I've followed some tutorials and managed to successfully retrieve the user's Twitter feed. However, when I tried implementing a hashtag URL, I encountered an e ...

Tips for ensuring sequential execution of $.post requests without ajax alternative

Can I make synchronous requests with $.post in this code snippet? function loadTest() { var questionIDs = []; var count = 0; console.log("getting test"); $.post("db.php", function(data) { obj = jQuery.parseJSON(data); var questionCount = obj.l ...

UI experiencing issues with selecting radio buttons

When trying to select a radio button, I am facing an issue where they are not appearing on the UI. Although the buttons can be clicked, triggering a function on click, the selected option is not displayed visually. <div data-ng-repeat="flagInfo in avai ...

Navigating the concepts of NodeJS and AngularJS can be a bit overwhelming

Having recently dabbled in creating simple single page applications using AngularJS without the need for a server, I decided to take a NodeJS course today. As I delved into the course material, something started bothering me. When using NodeJS, I realize ...

Scaling a plane in Three.js to cover the entire screen

My process of adding a plane to the scene goes like this: // Setting up Camera this.three.camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 60); // Creating Plane const planeGeometry = new THREE.PlaneBufferGeometry(1,1,thi ...

What is the best way to modify the state of a particular element in an array when using useState in React?

In my Next.js application, I am using a useState hook to manage state. Here is how my initial state looks like: const [sampleData, setSampleData] = useState({ value1: '', value2: '', value3: [] }); To update the state ...