Use either lodash or a for loop to organize a group of JSON objects

Here is the array I am working with:

[
  {
    corequisite: "",
    curriculumYr: "2017-2018",
    programCode: "ET"
    majorCode: "AET",
    prerequisites: "GMRC 101||Math 101"
    semester: "1st Term",
    year: "1st Year",
    subjectCode : "ENG 101",
    units : "9"
  },
  ...
]

<p>I am attempting to group this data by <code>programCode,curriculumYear and majorCode. From there, I want to further group it by Semester and Year.

Additionally, I am looking to create an array of the prerequisites and corequisites, splitting the subjects using the delimiter ||.

Below is an example of the desired output:

[
      curriculumYr: '2017-2018',
      programCode: 'ET',
      majorCode: 'ATO'
      ,{ Sem: [
              subjects : [{
                             Corequisites: ['Subj1','Subj2'],
                             Prequisites: [],
                             subjectCode: "Sample1"
                           },
                           ...],
              term: "1st Term"
            }],
            [{ 
               subjects: [2nd term subjects here], 
               term: "2nd Term" 
            }]
       Year: "1st Year"
   }],
   
   ...

The format remains the same for both the 1st and 2nd Years' 1st and 2nd Terms.

Despite attempts using angular-filter and lodash libraries, I have encountered varying results. Any guidance or assistance on this matter would be greatly appreciated!

Thank you in advance for your help!

Answer №1

When working with vanilla JavaScript, you have the option to create a function that can handle the conversion, renaming, and grouping of data into a new nested array.

This function utilizes a hash table for each level of nesting and goes through the specified keys as grouping properties, adding a new array at each stage for the resulting set.

function getGrouped(array, keys, callback, children) {
    var result = [],
        hash = { _: result };

    callback = callback || function (o) { return o; };
    children = children || [];
    array.forEach(function (a) {
        keys.reduce(function (r, k, i) {
            var temp = {},
                key = a[k],
                target = k;

            if (Array.isArray(k)) {
                key = k.map(function (b) { return a[b]; }).join('|');
            } else if (typeof k === 'object') {
                key = a[Object.keys(k)[0]];
                target = k[Object.keys(k)[0]];
            }

            if (!r[key]) {
                r[key] = { _: [] };
                if (Array.isArray(k)) {
                    k.forEach(function (b) { temp[b] = a[b]; });
                } else {
                    temp[target] = key;
                }
                temp[children[i] || 'children'] = r[key]._;
                r._.push(temp);
            }
            return r[key];
        }, hash)._.push(callback(a));
    });
    return result;
}

var data = [{ corequisite: "", curriculumYr: "2017-2018", programCode: "ET", majorCode: "AET", prerequisites: "GMRC 101||Math 101", semester: "1st Term", year: "1st Year", subjectCode: "ENG 101", units: "9" }, { corequisite: "SOFTENG1||SOFTENG2", curriculumYr: "2017-2018", programCode: "ET", majorCode: "AET", prerequisites: "COMP 1", semester: "1st Term", year: "1st Year", subjectCode: "THESIS101", units: "9" }, { corequisite: "", curriculumYr: "2017-2019", programCode: "ET", majorCode: "AET", prerequisites: "Sample1||Sample2", semester: "2nd Term", year: "1st Year", subjectCode: "SampleSubj101", units: "9" }, { corequisite: "", curriculumYr: "2017-2019", programCode: "ET", majorCode: "AET", prerequisites: "SSSS4||S6", semester: "1st Term", year: "2nd Year", subjectCode: "S1", units: "9" }, { corequisite: "SSS2||SSS4", c...

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

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

Express.js | Utilizing express.Router and handling route parameter inputs

I'm currently facing an issue with a small program I'm developing to practice Express.js. The problem lies in a separate router that is supposed to send a specific response based on the route. For example, when navigating to "/santiago", it shou ...

What is the best way to deduct a variable's previous value from the final value, ensuring that the total value does not surpass a specific limit?

For instance: let num = 20; const sub = 6; const add = 10; num = num - sub; num = num + add; if (num > 20){ num = 20; } console.log("Only 6 was actually added to var num before reaching its maximum value"); Is there a way to adjust the console log ...

Implementing Android Volley framework

Hey folks, I could really use some assistance! I'm a beginner with Volley and have been tackling login and registration using it. Specifically, I'm struggling with inserting and retrieving data in the database using JSON arrays and objects. Below ...

Having trouble retrieving a path reference from Firebase Storage using getDownloadURL() in React Native?

I am having trouble uploading some images and retrieving them using the .getDownloadURL() method. Oddly enough, it works perfectly fine in another part of my application when I update the user's profile picture, but for some reason, it fails in the co ...

What's the best way to enable touch scrolling for items within a div container?

I am in the process of creating a code snippet that will allow users to scroll through items within a div, similar to a spinning wheel or slot machine. While I am aware of an existing solution for iPhone and iPod, I want to develop a simpler, more streamli ...

Steps to display a div on top of a background image

Here is a visual representation of my design for better understanding: I am currently working on developing the central content that overlays the image. However, when I insert divs with background colors into my HTML to test their placement, I do not see ...

Error encountered while utilizing the infinite-react-carousel package in React

After entering "npm i infinite-react-carousel --save" into the terminal, an error message appears: "npm ERR! code ERESOLVE "npm ERR! ERESOLVE unable to resolve dependency tree" What could be causing this issue? How can I troubleshoot and resolve it? I h ...

Engage with Vue.js and traditional JavaScript (plain) in your projects

Exploring the integration of Vue with regular JavaScript has presented a challenge. While some solutions online propose moving all functions to a Vue component, this approach proves impractical for complex or large functions. The task now is finding a way ...

next-pwa seems to be malfunctioning without any discernible errors in the production environment

The repository is publicly available // next.config.js const withPWA = require("next-pwa"); module.exports = withPWA({ pwa: { dest: "public", sw: '/sw.js' }, }); _document.js _app.js Live I have verified the fu ...

Is it possible to use a Jasmine spy on a fresh instance?

In need of assistance with testing a TypeScript method (eventually testing the actual JavaScript) that I'm having trouble with. The method is quite straightforward: private static myMethod(foo: IFoo): void { let anInterestingThing = new Interesti ...

Issue in TypeScript where object properties may still be considered undefined even after verifying using Object.values() for undefined values

I'm encountering an issue with TypeScript regarding my interface MentionItem. Both the id and value properties are supposed to be strings, but TypeScript is flagging them as possibly string | undefined. Interestingly, manually checking that id and va ...

Displaying NodeJS error messages directly in the main HTML file

After creating a form using NodeJs and implementing input validations that display errors when users enter incorrect values, I encountered an issue where the errors appear on a new blank page instead of within the main HTML file itself with stylish formatt ...

Using AJAX to retrieve additional JavaScript code or functions from the server

It's common knowledge that AJAX is often utilized to request a web part in HTML format from the server. However, is it feasible to use AJAX to request a script that includes functions? ...

Application crash imminent, alert: Uncaught TypeError detected - Unable to access property 'some' of undefined within React

My application has 3 sections. The first section consists of a form where users fill in details about watches, and the data is submitted using the submitHandler function. In the second part, users can enter watches from the first section. When a user click ...

The global class variable encounters an error when trying to assign the value of "socket" to it

Within my class constructor, I am setting up a Socket connection and then storing the socket parameter in a global class variable (this.socket_variable = socket) so that I can access it across all functions in the class. CODE const { Server } = require(&q ...

Text color wave effect - mimic a block of colors flowing through text

I'm experimenting with creating a unique text effect where, upon hovering over the text, it appears as though a block of color is passing through it. Inspired by the technique showcased in this first example (specifically for the word "Kukuri"), I ut ...

What is the best way to link a list of strings to an 8-character key?

On my WPF form, I have a ComboBox and a TextBox. The ComboBox contains options related to email addresses that the user will enter into the TextBox. I want each option in the ComboBox to be associated with an 8-character key, which will then be serialized ...

I am looking for the best way to convert a complicated JSON stored as a string into a dataframe using Spark and Scala

I am facing a challenge in creating a dataframe from a complex JSON in String format using Spark scala. My Spark version is 3.1.2 and Scala version is 2.12.14. The source data looks like this: { "info": [ { "done": "t ...

Angular 2, React, or any other modern framework.getList()?.map

I have experience working on multiple angular 1 projects and I absolutely enjoyed it. We have several upcoming projects where I need to recommend JavaScript frontend libraries/frameworks. With the decline of angular 1 and mixed reviews about angular 2&apos ...

What is the best method for resizing an SVG according to the size of my website's window?

I am attempting to implement a scalable settings icon SVG file that adjusts based on the window width. My approach involved creating a JavaScript function that alters the element's dimensions according to the window size, but unfortunately, this metho ...