Generating a dynamic SQL Insert statement based on an array object

I am currently working on a Typescript project where I am looking to optimize my Insert function by creating one Insert statement for all the elements in an object, rather than generating multiple Inserts for each array item.

Here is the code snippet of my current function:

public async insert() {

        let object = [{ cod: 'CO',
        file: 'CO_SER.csv',
        exists: 1},
      { cod: 'ES',
        file: 'ES_INS.csv',
        exists: 1 } ];


        for (let elem of object) {
            let insert = `INSERT INTO databaseID VALUES ("${elem.cod}", "${elem.file}", ${elem.exists})`;
        }

    }

Currently, the output looks like this:

INSERT INTO databaseID VALUES ("CO", "CO_SER.csv", 1)
INSERT INTO databaseID VALUES ("ES", "ES_INS.csv", 1)

However, I aim to achieve the following desired outcome:

INSERT INTO databaseID VALUES ("CO", "CO_SER.csv", 1), ("ES", "ES_INS.csv", 1)

Answer №1

const items = [
  { code: 'CA',
    doc: 'CA_ACCEPT.csv',
    valid: 1},
  { code: 'EN',
    doc: 'EN_INT.csv',
    valid: 1 } ];

let insertData = `INSERT INTO databaseRef VALUES ` + 
  items.map(
    item => `("${item.code}", "${item.doc}", ${item.valid})`
  ).join(', ')

console.log(insertData)

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 Express - Run a function on each incoming HTTP request

My local Node.js server has a function called unzip() that is responsible for downloading a .json.gz file from an AWS CloudFront URL () and unzipping it into a .json file whenever the server is started with node app.js. Prior to responding to routes, the ...

Can you explain the distinction between Observable<ObservedValueOf<Type>> versus Observable<Type> in TypeScript?

While working on an Angular 2+ project in Typescript, I've noticed that my IDE is warning me about the return type of a function being either Observable<ObservedValueOf<Type>> or Observable<Type>. I tried looking up information abou ...

Is it possible to merge a dictionary with text file writing and then retrieve it as a dictionary once again?

I am making requests to a link and receiving JSON files as response. I am storing this data in a text file, but when I try to read it back, I want to interpret it as a dictionary. How can I achieve this? def url_sequence(limit=5): for i in range(limit ...

What is the best way to implement a custom NgbDateParserFormatter from angular-bootstrap in Angular 8?

Currently, I am working on customizing the appearance of dates in a form using Angular-Bootstrap's datepicker with NgbDateParserFormatter. The details can be found at here. My goal is to display the date in the format of year-month-day in the form fi ...

The error message "React is not defined" is commonly encountered when using React Native Storybook with

While attempting to configure React Native with Storybook, I encountered an issue when importing a .tsx component. The error displayed was: React is not defined ...

Add JSON elements to an array

Looking for help! {"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]} Need to add these items to a jQuery array. I've attempted using JSON.parse without success. Typically, I can push parameters as follows: MyArr.push([& ...

"Convert a jQuery array into a JSON format compatible with PHP

Using jQuery, I am extracting various text nodes (p) and headers from a source and storing them into arrays: var textnode = $(source).children("p:not(:has(img))").map(function () { return $(this).outerHTML(); }).get(); var headerone = $(source).child ...

Tips for incorporating a list into a MongoDB query

I encountered a problem with my dynamic queries when using an array for the column value. For example, if col is an array like c("red", "blue"), the query fails to execute. Works fine with single value col<-"red" pipe1 <- paste("{&bsol ...

Does having an excessive amount of variable declarations result in a noticeable decline in performance?

One thing I notice for the sake of readability is that I tend to create new variables for data that I already have on hand. I'm curious, does this impact performance significantly? Here's an example of what I mean: const isAdult = this.data.per ...

How can I create a JSON output from my MySQL database that includes the total count of records per day for a Task entry?

I am looking to implement the JavaScript library called Cal-Heatmap (https://kamisama.github.io/cal-heatmap/) to create an Event style heatmap similar to GitHub's. The objective is to visualize the number of actions taken on each Task record in my Pr ...

JavaScript post method for JSON data: no input or output values

I am currently developing a page that extracts data from an HTML table consisting of two columns and an index of a form, and then converts it into a JSON string. The intention is to pass this data into PHP for further processing, perform calculations on th ...

Firebase data not appearing on screen despite using the async pipe for observables

My current challenge involves accessing data based on an id from Firebase, which comes back as an observable. Upon logging it to the console, I can confirm that the Observable is present. However, the issue arises when attempting to display this data on th ...

Utilize a JSON file to generate a network visualization using the vis.js library

I am currently working with vis.js to generate a visualization. In the example code, I am using the file saveAndLoad.html. The save function works well as it allows me to export a json file. However, I am encountering an issue when trying to load the jso ...

Authentication checkpoint within an Angular application using a JWT cookie

After searching extensively, I was unable to find a question that directly addresses my specific concern. Currently, I am working on a project involving an angular application that utilizes jwt and http-only cookies for authentication. In order to authenti ...

The `toString` function is displaying an array instead of the expected string

As a beginner in programming, I am currently enrolled in an introductory JavaScript course. However, I am facing an issue with my assignment where the toString method is printing an array instead of a string. Despite thorough research, I have been unsucces ...

Rollup bundling with Typescript and troublesome rollup-plugin-typescript2 experience

I'm currently facing some unexpected challenges while attempting to extract a small portion of a monorepo into a web client library. The issue seems to be related to the configuration of Rollup, as shown below: import resolve from "rollup-plugin-node ...

The primary route module is automatically loaded alongside all other modules

I have configured my lazy loaded Home module to have an empty path. However, the issue I am facing is that whenever I try to load different modules such as login using its URL like /new/auth, the home module also gets loaded along with it. const routes: R ...

Protected class, yet not transferable

My output varies based on the type of input provided. I have a custom guard in place to protect the input, but I'm still having trouble assigning it to the declared output: type InputType<Sub extends SubType> = { a: Sub, b: string } type SubTyp ...

IE9 encounters a setback with AJAX Jsonp request

Below is the code snippet I am working with: $.ajax({ type: 'POST', url: 'index.jsp', data: 'id=111', dataType: 'jsonp', success: function(data) { alert(data.result); }, error: f ...

Guide on creating a Typescript function with a strongly typed argument

I am looking to develop a function that accepts a type created using export class and imported in the traditional manner as an extension of a particular type. With a base Page class and various derived classes, I aim to have this function capable of receiv ...