Methods or tools for transforming the output of a query into JavaScript objects

I am working with a basic database schema that includes parent-child relationships spanning 2 to 3 levels deep. An example of this is:

  • School has many teachers
  • School has many departments

Currently, my query produces a flat table output like this:

school  teacher  department
CMU     John     Engineering
CMU     Julie    Engineering
CMU     John     Humanities
CMU     Julie    Humanities

While ORM tools can return results as objects, I find them too cumbersome for my needs. Are there any straightforward algorithms or libraries available to transform this result into hierarchical object structures, perhaps in JSON format like this:

{
    departments: [
        'Engineering',
        'Humanities'
    ],

    teachers: [
        'John',
        'Julie'
    ]        
}

This could also be extended for a 3-level deep relationship with a different query and result set:

{
    departments: [
        {
            name: 'Engineering',
            teachers: [
                'John',
                'Julie'
            ]
        },
        {
            name: 'Humanities',
            teachers: [
                'Mike',
                'Mary'
            ]
        }
    ]
}

Answer №1

When it comes to databases, each one has its own unique features. For example, Postgresql offers functions that can efficiently structure query results into JSON format. If you're curious about this capability, check out this informative article

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

Improving Performance of a Large Unordered List using JavaScript

My website currently features a search box that retrieves images and displays them in a list format. Each image has an associated click event that triggers an overlay on the parent li element when clicked. However, with search results exceeding 300 images ...

Looking to refine the MySQL result set even more?

Upon examining the records, I have found the following patterns: 21 | 42 | 387 32 | 42 | 387 23 | 42 | 397 45 | 42 | 397 25 | 42 | 700 25 | 53 | 397 27 | 53 | 700 My goal is to refine this data further. I have created queries for service IDs 387, 3 ...

Allow only specified tags in the react-html-parser white list

Recently, I've been working on adding a comments feature to my projects and have come across an interesting challenge with mentioning users. When creating a link to the user's profile and parsing it using React HTML parser, I realized that there ...

Guidelines on extracting all choices from a select element and organizing them into a list

Is there a way to retrieve the HTML content of all the options in a list using jQuery (or native js)? The desired output should be something similar to: var options = ['<option value="" selected="">---------</option>', <option val ...

Execute an ajax request when the button is clicked

I am facing an issue with a button that is supposed to trigger a function involving an ajax call and other tasks. Despite setting the button's id for a click function, I am unable to generate any response upon clicking. $.ajax({ type: "GET", ...

Is it possible to include a record as a parameter in an INSERT statement?

I need to populate a new table called T. create or replace procedure extractData is cursor c1 is SELECT a.id, a.data, b.id, b.data, c.id, c.data FROM a LEFT JOIN b ON a.id = b.id LEFT JOIN c on b.id = c.id; begin for currRec in c1 loop insert into tabl ...

Enhanced file sorting capabilities implemented through the addition or removal of just 2 lines of code

SELECT test2.*, account.* FROM test2 JOIN account on test2.account_id = account.id where test2.id > 0 and test2.active = TRUE and account.age BETWEEN 18 AND 80 AND account.gender = 'MALE' ORDER BY test2.id DESC LIMIT 20 CREATE TABLE `ac ...

Refresh the text area with the latest information received from the servlet using JavaScript

I am currently working on a program that involves calling a JavaScript function with multiple requests to a servlet. My goal is to execute these requests one by one and receive a response after each execution. However, the function I have only displays the ...

Generating dates in SQL from two given dates

I'm currently working on creating a view that tracks Active and Ceased Services. Using the Put into Service date and ceased date, I need to generate monthly trends for both active and ceased orders. The query should be able to automatically generate t ...

When applying json_encode to the PHP $_GET array, it returns a singular string instead of an array containing strings

I am attempting to utilize the PHP GET method in order to generate an array of keywords from a keywordBox field on a different page. For instance, here is how the keywords are added to the page URL: /searchResults.php?keywordBox=computing+finance Althou ...

What type of data is most suitable as the primary key for large-scale identification in databases?

In my database, I am facing the challenge of storing a primary key with a length of 21 characters, such as a Google or Facebook user id. This exceeds the maximum values that an int (2147483647) or BIGINT (9223372036854775807) can hold. After researching, ...

Leveraging AJAX Post Data in NodeJS using Express

I'm currently working on retrieving the values I send for an ajax post within my node application. After referring to a helpful post on Stack Overflow, here is what I have implemented so far: Within Node.js: var express = require('express&apos ...

Is axios allowed to be used in this scenario?

As a newcomer to web development, I apologize in advance if my question seems basic or if the details provided are insufficient. Nevertheless, I hope you can assist me with the following query: Is it possible to execute an axios.post request within a vue. ...

Incorporate a new tab based on specific conditions in Excel 2016/365 using office add-ons (Javascript API)

I am currently in the process of developing an Office Add-in for Excel that requires the addition of a worksheet conditionally. I need to ensure that if the worksheet is not already present, it must be added and filled. If it already exists, I just need to ...

Transmitting information via ajax in a React.js application

Here is the React code that I have: var AddRecord = React.createClass({ componentDidMount: function() { }, render: function() { return ( <form action="process.php" method="post"> <table><tr>< ...

How to eliminate the hash from a particular page in VueJS

My dilemma is quite similar to the one discussed in this Vue router thread on removing hash on certain pages I need to configure the hash mode for all pages except for mysite.com/success. This specific page is accessed via redirect from ...

Is there a way to remove specific items from my array in Vue.js?

Essentially, I am using an HTML select element that is populated with arrays of registered users. <label > <b> <i style="opacity:0.8">Users:</i> </b> </label>&nbsp;&nbsp; <select class=&quo ...

Develop a dynamic button using JavaScript to fetch information from an array

I'm struggling with incorporating this button creation code into my HTML using JavaScript. The code for creating the button element in JS file looks like this: var numery = ['A','B','C']; var numer = document.createE ...

"Transforming the Website Background with a Splash of Color

I am trying to figure out how to change the color scheme of my website with a button click. Currently, when I select a different color, only the background of the webpage I'm on changes, not the entire website. I have applied CSS but it's not ref ...

What is the best way to locate a DOM element using jQuery after I have repositioned it on the page?

I designed a page that consists of two sections, with boxes in each. The functionality I implemented allows users to click on a box in either section and move it to the other section. Initially, this feature works smoothly for the first movement. Theoretic ...