How can I extract the parameters stored in a JSON object inside a function() call using RegExp.$?

I am attempting to extract a set of parameters for RegExp.$ (also known as JavaScript f-strings) from a JSON file.

const schema = require('../schema.json').Flights;
class flightRepo{
    keys = Object.keys(schema);

    create(db) {    
        return client.query(
            "INSERT INTO flights ($1, $2, $3, $4, $5, $6) VALUES ($7, $8, $9, $10, $11, $12)",
            keys[0], keys[1], keys[2], keys[3], keys[4], keys[5],
            db.schema.keys[0], db.schema.keys[1], db.schema.keys[2], db.schema.keys[3], db.schema.keys[4], db.schema.keys[5]
        );
    }
}

ABOUT
client.query: Utilizes the Client Object from Deno's PostgreSQL Library
db: Receives a list [args[0-5] for each key] to generate a new DB entry
create: Function returns the query status obtained from PostgreSQL

JSON STRUCTURE

{
    "Flights" : {
        "FlightNo": "INT PRIMARY KEY",
        "Airlines": "STRING 50",
        "Time"": "DATETIME",
        "OnTime": "BOOLEAN",
        "Dep": "STRING 4",
        "Arr": "STRING 4"
    }
}

My goal was to eliminate the manual specification of n args (keys[0-5]) and ($1-12), and instead come up with an expression that can handle any x-item key list.

(plus, finding a way to omit the need to enter "Flights" as the JSON key in Line 1 would be beneficial)

Answer №1

To adjust the code for varying number of keys, use $# tokens based on the keys array in a template literal and spread notation for spreading out the arrays; refer to comments:

const schema = require('../schema.json').Flights;

class flightRepo {
//    ^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− capitalizing convention should be followed here
    keys = Object.keys(schema);

    create(db) {    
        return client.query(
            `INSERT INTO flights (${keys.map((_, i) => `${i + 1}`)}) VALUES (${keys.map((_, i) => `${i + 1 + keys.length}`})`,
            ...keys,
            ...db.schema.keys // Assuming `db.schema.keys` has the same length as `keys`
        );
    }
}

It would be helpful to find a way to eliminate entering the "Flights" JSON key in Line 1

To specify which part of the object you need, utilize destructuring with renaming:

const {Flights: schema} = require('../schema.json');

...however, maintaining the current naming might offer better clarity. Alternatively:

const {Flights} = require('../schema.json');

...utilize Flights instead of schema. But if it's not a constructor function, using uppercase may lead to confusion.

Since Flights appears to be the only property in the JSON example, you can try this:

const data = require("schema.json");
const schema = data[Object.keys(data)[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

Configuring an Android application by parsing JSON data

I am currently working on an Android app where I need to utilize JSON data from a server to make specific adjustments within the app. My goal is to parse this JSON and store all the values in local variables to perform actions in the app. JSON From Server ...

Identify the moment when the user modifies the sequence of a sortable table

I am currently exploring methods to detect when a user changes the order of rows in a sortable table. The table structure is as follows: <table class="table table-striped table-hover" id="captureTable"> <thead> <tr> ...

What is the best way to swap the values of options between two input select elements?

I am trying to create a feature where I have two select dropdowns with the same options, and when a trigger is clicked, the option values are inverted between the two selects. Here is an example: <select id="source_currency"> <option value="BRL" ...

Looking to access the layout details of an HTML element similar to what can be done in Firefox's debugger tool?

I am facing a challenge with a aspx.net grid control where I need to extract the first row's information and copy it into another table using JavaScript. To achieve this, I am attempting to calculate the width of each cell in the first row by accessin ...

The instance is referencing "greet" during render, but it is not defined as a property or method

At the same time, I encountered another error stating "Invalid handler for event 'click'". <template> <div id="example-2"> <!-- `greet` is the name of a method defined below --> <button v-on:cli ...

"We are experiencing issues with the app.get function and it is

Although my backend is successfully serving other files, I have encountered an issue with loading new files that are located in a folder named js within the directory. These specific files are not being loaded, and despite spending an hour trying to troubl ...

What steps should I take to integrate my Node.js code into a website successfully?

I have a node.js code that works perfectly in the terminal. How can I display the console.log output on localhost and later on Heroku? Since I am still a beginner, I find express challenging. Do you think I should use it? I also tried Browserify. const p ...

In Laravel, Inertia.js will automatically close a modal if there are no validation errors present

Here is the method I am currently using: methods: { submit() { this.$inertia.post('/projects', this.form); this.openModal = false; }, }, Unfortunately, this method closes the modal even if there are validation erro ...

Maintaining parameter values through multiple states using Angular and UI-Router

I am attempting to create a intricate URL structure: http://example.com/quote/:param1/:param2/:param3/:param4 With the exception of one, each state utilizes the same template. My inquiry is whether there exists a method to dynamically transfer each para ...

The Node.js response triggers an error message stating: 'SyntaxError: JSON.parse: unexpected end of data.'

My attempt to establish a connection between Node and a simple form using AJAX involved two key files. The first file is an HTML document containing a textbox and a button. The second file is the Node server responsible for handling requests. The goal w ...

Utilizing Dictionary Comprehension to Filter Key/Value Pairs Based on Conditions in API Response

I have gathered a collection of API responses under the name `user_responses'. Here is an example from the list: { "ok": true, "members": [ { "id": "W012A3CDE", "tea ...

Alternating Text Color jQuery Sequencing

I'm having trouble deciding on the most effective approach to achieve this task. My goal is to animate the color change of a div's text in a specific sequence (e.g., #000, #eee, #fff...) every 1.5 seconds. From my research, I gather that I will ...

How to extract iframe page title with jQuery in JavaScript

Is there a way to retrieve the title of an iframe's source page and then update the title of the main page? ...

Safari's mysterious vanishing act: Elements go missing in Vue.js

Has anyone encountered this issue before? I am using a vue 2 template with vuetify 2 for rendering, and I have noticed that in Safari only, the buttons on the page flash upon loading and then disappear. Upon inspecting the DOM, I can still see the button ...

Explore the format outlined in the setup file

I am working on creating a configuration reader in C/C++ using Low-Level I/O. The configuration file contains settings like: App example.com { use: python vauejs sass; root: www/html; ssl: Enabled; } I am trying to figure out how to rea ...

Validation of textfields using React.js

Currently, I am working on implementing a validation feature in ReactJS. Specifically, I have a field named "name" and my requirement is that every time a name is entered, it must be equal to or greater than 2 characters. The validation works fine when t ...

Unresolved styles in React component linked to styles.css file

As I dive into creating a registration page in ReactJS, I encounter a frustrating issue with my styles not applying correctly from the styles.css file. Let's take a look at my RegisterPage.jsx component: export default function RegisterPage() { ret ...

What is the best way to use form input to filter an Observable?

Within my component, I have declared the variable "countries$": countries$!: Observable<Country[]>; To populate this variable with data from this API, I use the following code in the "ngOnInit" lifecycle hook: ngOnInit(){ this.countries$ ...

Heroku's Ban on Loading Mixed Content over HTTP

Currently, I am in the process of developing a web application using Node.js and Express. Everything seems to be functioning properly when I deploy my project to Heroku; however, I encountered an issue whenever I attempt to execute any action that involves ...

No data coming back from API in JSON format

Can anyone help me figure out what I'm doing wrong? I've been using the sample code from the API documentation (https://github.com/bitmarket-net/api), but the JSON response is empty. All I did was add echo bitmarket_api("info"); and replace the ...