Creating an array by combining two queries using loops: What's the best approach?

I am trying to set the primary array to have the property of a foreign key

I have two tables, tipe_akademik and jam_akademik_a

The jam_akademik table has a foreign key pointing to tipe_akademik

My goal is to display tipe_akademik as having a list of jam_akademik_a, referred to as list_mapel

This is how I want the array to look like:

{
    "data": [
        {
            "id": 1,
            "tipe_akademik": "a",
            "listmapel": [{//from jam_akademik_a//
                    "id": 1,
                    "mapel": "Pendidikan Agama Islam",
                    
                    "tipe_aka": 1
                },
                {
                    "id": 10,
                    "mapel": "Bahasa Indo",
                    
                    "tipe_aka": 1
                }
            ]
        }, and etc

In my array, the first ID is the primary key from tipe_akademik, and tipe_aka is a foreign key pointing to that ID. I am attempting to combine the results of two queries into one array.

Here is a snippet of my source code:

router.get('/test', function (req ,res) {

  
    //query
    
    let tipe= []
   
    connection.query(`SELECT * FROM tipe_akademik  `,  function (err, result){
         tipe=result
       
         let i = 0
for (let mapeltipe of tipe ){connection.query ('SELECT * FROM jam_akademik_a WHERE tipe_aka = ? '  ,[mapeltipe.id] ,function (err, listmapel){
    tipe[i].listmapel = listmapel
i++

}

)}return res.status(500).json ({data: tipe}) 
    }
    )

});

However, when I return it, the tipe array still only shows the results of the first query. The looping I attempted to do to combine the two queries is not saving the data in the tipe array. I would appreciate any help in resolving this issue and combining the two queries into one array.

Answer №1

There are two essential steps that need to be taken.

  1. When working with a callback function, your return statement may not work as anticipated. You will need to utilize await to retrieve the results. It is advisable to explore the concept of JavaScript async/await for a deeper understanding. This reference thread might offer some assistance.
  2. Assuming that your tables are linked via a foreign key, it is recommended to leverage this relationship in your SQL query. Instead of manually processing data in JavaScript, utilize the database functionalities by performing an INNER JOIN to combine (intersect) the two tables. I suggest researching SQL JOIN for further insights.

By implementing these adjustments, you can achieve a solution resembling the following.

Disclaimer: The following code is hypothetical and assumes certain database field names to construct the query. However, the concept should function.

// Ensure the function is async to utilize async
router.get("/test", async function (req, res) {
  // Wait for the Promise to be resolved or rejected
  const data = await getDatabaseData();
  return res.status(500).json({ data: data });
});

async function getDatabaseData(){
  // Return a Promise immediately and handle the callback results
  return new Promise((resolve, reject) => {
    // Attempt to JOIN if a foreign key is present, refer to SQL JOIN for examples/ explanations 
    connection.query(`SELECT * FROM tipe_akademik AS t INNER JOIN jam_akademik_a AS j ON j.listmapel = t.tipe_aka;`, (err, result) => {
      // Reject the promise if an error occurs
      if(err) reject(err);
      // Resolve the promise with the data
      else resolve(result);
    })
  })
}

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

Arranging money in Visual Basic .NET

Struggling with a currency sorting bug in our internal software built with VB.NET. The issue lies within a DataGridView holding values. Here's the code snippet: SQLReader.Read() Code As a result, the Value Column is incorrectly sorted Further down ...

JavaScript: Accessing the selectedIndex of a dropdown list in RadGrid

Currently facing an issue with utilizing the RadGrid control from Telerik. I am attempting to access and manipulate the value of a GridDropDowncolumn within RadGrid using JavaScript (while in edit mode). Does anyone have any suggestions for the correct Ja ...

AngularJS testing typically involves the use of the inject module injection process

Currently, I am working on testing a service called documentViewer, which relies on another service named authService. angular .module('someModule') .service('documentViewer', DocumentViewer); /* @ngInject */ function Do ...

Retrieving Information from a Database with a Checkbox Selection Array

After successfully creating a View that cycles through a database table to populate checkbox option titles based on data from the database, I encountered a new challenge. Here's an example of the code snippet: <?php foreach ($bud_items_si as ...

Is there a way to identify consecutive sets of identical elements within a list?

I am in need of creating a function that takes a list of integers L and an integer n. The goal is to determine if the list contains a consecutive sequence of ones with a length of n, returning True if it does, and False otherwise. For example, let's ...

jQuery loops through form fields and sets them as disabled

Trying to solve a question... In a form with multiple inputs, I only need to loop through the ones inside the div tagged player. <div class="player"> <input type="text" value="0" class="unit" /> <input type="text" value="0" class="unit" ...

Tracking global click events in Vue.js can provide valuable insights into user interactions on your

While working with JavaScript, I was able to create this code for a popover. By clicking on the navbar-link element, the popover will appear or disappear. However, it would be great if I could close the popover by clicking anywhere on the screen (when the ...

What is the best way to prompt Leaflet to refresh the map display?

I'm facing a challenge while integrating Leaflet with React, where Leaflet seems to want control over the DOM rendering as well based on my research. Currently, I have countries being properly colored according to specific color codes derived from ba ...

What is the method for adding up a string in PHP?

Here's a quick question for you: So I have this variable: $v = "24000,1500,1500,1500,1500,1500,"; I want to add all these numbers together. I attempted to use str_replace to replace the commas with plus signs and then use eval(), but that didn&apos ...

Animating the scaling of a background image with JavaScript resulted in a jittery, unstable image

I'm encountering a shaking effect when I animate a DIV container with a background image using JS. How can I make the animation smoother? $('body').on('click', '#container', function() { $("#container").animate({ ...

I am having trouble displaying images with Material UI CardMedia

I'm currently using CardMedia to display images on my webpage, but unfortunately, the image is not appearing as expected. After researching a similar issue on Stack Overflow, I discovered that the suggested solution involved importing the image and t ...

The child_process module in Typescript is unable to recognize execSync as a valid function and returns

Currently, I am attempting to utilize the execSync function from the child_process module. However, after importing the module: /// <reference path="../../../../GENERAL/d.ts/node/node.d.ts" /> var execSync = require("child_process").execSync; Upon ...

The srcSet functionality in the Image component seems to be malfunctioning in the next.js framework, as it is failing to display

Check out my Next.js code snippet below: import React from "react"; import style from "@/styles/Home.module.css"; import Image from "next/image"; function index() { return ( <> <div className="contai ...

Need assistance with a sophisticated sql query? Feel free to inquire about a

Two tables exist: one for members and one for vouchers. Each member can have multiple vouchers, and each voucher can be associated with multiple members. Here is an example scenario: Member A has vouchers 1 and 2. Voucher 1 is associated with members A, ...

What is the method for referencing variables in a JSON response?

Utilizing the Steam API, I made a call to retrieve a response and then formatted it using the paned code: $url = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key='.$key.'&steamids='.$id; $json = json_decode(fi ...

React isn't updating the on-change value despite changes being made

In my React application, there is a file called EditTodos.js that is responsible for updating the to-do list. When I click on the "Edit" button, it triggers a pop-up modal component. import React, { useState } from "react"; import { Button, Modal } from " ...

Is it possible to host multiple React applications on a single port? Currently experiencing issues with running both an Admin panel and the Front side in production mode on the same Node.js API server

Is it possible to host multiple React applications on the same port? I am experiencing issues with running both an Admin panel and a Front side React app in production mode on the same Node.js API server. ...

Issue with Javascript Date and Time Validation

My application includes code that is supposed to display HTML pages based on today's date and the time of day (morning, afternoon, or evening). However, it seems like there is an issue with how the time is being checked. Currently, at 2:53pm, only the ...

Encountering the 'data is null' error when making a Twitter API request, yet the data is successfully displayed in the browser

I am attempting to show the number of followers for a Twitter account, but when I connect to the API using this code: $.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true", function(data) { console.log ...

Is there a way to trigger the interval on the second load and subsequent loads, rather than the initial load?

I have implemented the use of setInterval in my recaptcha javascript code to address the issue of forms being very long, causing the token to expire and forcing users to refill the form entirely. While I am satisfied with how the current code functions, t ...