Creating MySQL query results in Node.js manufacturing process

I am looking to format the MySQL result in Node.js in a specific way. The desired result format should look like this:

[ 
 { 
 "m_idx" :1 ,
 "contents" :
             { 
               "m_name" : "a",
               "m_name" : "b",
             }
 },
 "m_idx" :2,
 "contents" :
             { 
               "m_name" : "c",
             }
 }
]

However, my current result does not match this formatting. It looks like this:

{
        "m_idx": 1,
        "contents": [
            {
                "m_name": "a"
            }
        ]
    },
    {
        "m_idx": 1,
        "contents": [
            {
                "m_name": "b"
            }
        ]
    },

I am unsure of how to achieve the desired result. Can anyone provide assistance? Below is the code that I have been working on:

let result = [];
    let categories = [];
    connection.query(sql, function (err, rows) {
        if (res.status(200)) {
            rows.forEach(function (row, index) {
                    let variable = {
                        m_idx: row.m_idx,
                        contents: []
                    };
                    categories.push(variable);
                    variable.contents.push({
                        m_name: row.m_name,
                        name: row.name,
                    })
            });
            res.json(categories);
        }
    });

This is an example of the data structure in my database:

-----
|1|a|
|1|b|
|2|c|
-----

Answer №1

It seems like you are looking for an array instead of an object because objects should not have duplicate properties.

Here is a suggestion that might assist you:

const rows = [
  {"id": 1, "name": "a"},
  {"id": 1, "name": "b"},
  {"id": 2, "name": "c"}
]

const map = new Map();
rows.forEach(row => {
  if (map.get(row.id) === undefined) {
    map.set(row.id, {
      "id": row.id,
      "contents": [{"name": row.name}]
    });
  } else {
    map.get(row.id).contents.push({"name": row.name});
  }
});

const result = [];

map.forEach((value, key) => {
  result.push(value);
});

console.log(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

Node.js implementation for routing WebSocket requests from an HTTPS server to an HTTP server

I'm currently developing a Node.js proxy server that handles routing requests from a website to a local endpoint. The website has the capability to run either on a local server or in a cloud instance, so the proxy needs to be able to support both HTTP ...

The absence of essential DOM types in a TypeScript project is causing issues

Recently, I've been working on setting up a web app in TypeScript but I seem to be missing some essential types that are required. Every time I compile using npm run build, it keeps throwing errors like: Error TS2304: Cannot find name 'HTMLEleme ...

In need of a collection of modules determined by a DefinePlugin constant

Currently, I am in the process of constructing a web application utilizing Webpack. However, I have encountered a challenge with a particular aspect of the design - hopefully someone in this forum has experience in similar tasks (or possesses enough knowle ...

The event listener $(window).on('popstate') does not function properly in Internet Explorer

$window 'popstate' event is not functioning properly in IE when using the browser back button. Here is the code snippet used to remove certain modal classes when navigating back. $(window).on('popstate', function(event) { event.pre ...

Steps to remove TLS 1.0 and 1.1 server-side support for my application running on AWS

Currently, I am tasked with improving a Node.js application. The existing code utilizes the http.createServer() method to set up a server. Since SSL configurations are managed at a level above the application code, the https object with certificate options ...

What is the reason behind mongoose's utilization of schema, especially when MongoDB is known for its schema-less nature?

Just diving into the world of mongodb and feeling like a complete newbie. I've been utilizing mongoose to interact with mongodb through node.js, and while everything seems to be functioning properly, I can't help but wonder about the rationale be ...

Encountering npm install failure post updating node version

When attempting to execute npm i, the following error message is now appearing: npm i npm ERR! path /home/ole/.npm/_cacache/index-v5/37/b4 npm ERR! code EACCES npm ERR! errno -13 npm ERR! syscall mkdir npm ERR! Error: EACCES: permi ...

Attempting to create an animated carousel slider

I've been working on creating a carousel animation that displays 3 images, slides them to the left, and brings in new ones. I'm feeling a bit stuck and could use some assistance. Check out my work so far on this fiddle link: http://jsfiddle.net/ ...

Is there a method in AngularJS to submit form data when the input fields are pre-populated using a GET request?

How do I submit form data in AngularJS? I have a div that populates the input field from a GET request. Now, I want to send this data using a POST method. How can I achieve this? Below is the form div: <div class="row" ng-app="myApp" ng-controller="myC ...

Tips for making an image fill the entire screen with a header using React Navigation

My screen includes an image and I would like to capture the full-size screen with the header displayed. However, using position: "absolute" does not properly wrap the header, and setting header: null is not an option since I still want the back button to b ...

Tips for incorporating a visible marker beside the dropdown arrow

When developing my React application with React hooks forms, I have a select component where I need to include a clear indicator 'x' icon next to the dropdown icon. The current select component code is: <Form.Control size="sm" as=&q ...

When I type text into the form field, JavaScript causes a disruption in the form

I'm attempting to implement a dual-stage user onboarding procedure. Initially, users will input the industry they belong to and then provide a description. Upon clicking submit, my intention is to conceal that portion of the form and reveal the "Creat ...

Seeking guidance on designating an additional disk for fs.readdir(path) within an Electron-vue application?

Issue: I am facing a problem with the breadcrumbs component in my project, which is utilizing file explorer functionality from this specific project. The issue at hand is related to changing the disk being displayed by the component. Upon clicking on any ...

A more intelligent approach for generating JSON responses using Mysql

Here is the code I have on my server side using Node.js: var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'SOMEUSER', password: 'SOMEPASSWD', database: 'SOMED ...

Exploring Nextjs with server-side rendering and fetching data from

When utilizing the getServerSideProps function in Next.js to make a fetch request to my API, I encountered an issue where the origin header was coming back as undefined. This seems to be specific to requests made from the server in Next.js, as I am able ...

Encountering the error "ERR_HTTP_HEADERS_SENT" after attempting to send emails through the next.js API

Currently, I am in the process of generating users through the next.js API. However, my goal now is to utilize SendGrid for sending emails. The setup is in place, but unfortunately, I'm encountering the following issue: event - compiled successfully ...

Tips for organizing JSON object data and displaying it appropriately on an HTML page

This code utilizes ajax: $("form").on("submit", function () { var data = { "action": "test" }; data = $(this).serialize() + "&" + $.param(data); $.ajax({ type: "POST", dataType: "json", url: "ajax2.php" ...

Ordering data in GraphQL by its unique identifier

After downloading a simple tutorial code, I found myself struggling to figure out how to sort by ID in GraphQL while playing around with it. Here is the query.js file: import React from "react"; import { useQuery } from "@apollo/react-hooks"; const Quer ...

The controller in AngularJS fails to function properly after the initial page refresh

I am currently utilizing AngularJS in my hybrid Ionic application. Here is my controller: .controller('SubmitCtrl', function($scope) { console.log("It only works when the page is refreshed!"); }); The console.log function runs perfectly fine ...

Failure occurs when attempting to install pods in an integrated development environment compared to

Currently encountering an issue while attempting to execute a pod update from the terminal within my Integrated VS-code environment on a react-native project. The error message received is as follows: node:internal/modules/cjs/loader:936 throw err; ^ ...