Generating a dynamic SQL Update statement using an array of objects

I am currently working with an array of objects in order to create an Update SQL statement. Here is the array I am using:

let dataUpdate = [
  {
     "field1":123,
     "field2":"BMW",
     "field3":"blue"
  }
]

This is my attempted approach:

let query: string = `UPDATE dataset.table SET` + dataTest.forEach((item:any) =>
  Object.entries(item).map(([key,value]) => {
    `${key} = '${value}'`
  }).join(',')
)

After running this code, I end up with:

UPDATE dataset.table SETundefined

What I actually want to achieve is:

UPDATE dataset.table SET field2="BMW", field3="blue" WHERE field1=123

Answer №1

It is essential to distinguish between the criteria and the update in your code structure. I have implemented a function named updateQuery, which generates the required query as shown below.

const quote = (val) => typeof val === 'string' ? `"${val}"` : val;

const updateQuery = (table, criteria, update) =>
  `UPDATE ${table} SET ${Object.entries(update)
    .map(([field, value]) => `${field}=${quote(value)}`)
    .join(', ')} WHERE ${Object.entries(criteria)
    .map(([field, value]) => `${field}=${quote(value)}`)
    .join(' AND ')}`;

const expected = 'UPDATE dataset.table SET field2="BMW", field3="blue" WHERE field1=123';

const actual = updateQuery(
  'dataset.table',
  { 'field1': 123 },
  { 'field2': 'BMW', 'field3': 'blue' }
);

console.log(expected === actual);

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

New and Improved React Material Collapse with onClick Event [Answer Refreshed]

I am currently working on a component that contains a list of details. Each item in the list has a "Details" button, and when clicked, it should show additional information only for that specific item. I am using Material-Ui with React and have imported ...

Search through array elements that are nested deeply

Consider the following scenario: an array is provided as input containing various objects with nested elements. The goal is to filter this array in JavaScript and obtain a new array consisting only of objects where the key "navigation" has a value of true. ...

Insert a hyperlink button using InnerHtml

I am facing an issue with displaying a list item that contains a tab and a link button: <li runat="server" id="liActivityInvoices"><a href="#tabActivityInvoices">Invoices</a><asp:LinkButton runat="server" ID="btnLoadInvoice" OnClick=" ...

Unable to dynamically add an element to a nested array in real-time

I'm currently developing an angular tree structure that contains a large nested array. nodes : public fonts: TreeModel = { value: 'Fonts', children: [ { value: 'Serif - All my children and I are STATIC ¯\ ...

When you start scrolling down, the JavaScript menu will cleverly disappear, only to re

I am facing an issue with my menu, which is a normal block-displayed div. There is another div with annotation above it. I want the menu to stick to the top as fixed when scrolling down, but immediately hide itself. The goal is for the menu to appear when ...

Angular data table is currently displaying an empty dataset with no information available

While attempting to display a data table in Angular JS, an issue arose where the table showed no available data despite there being 4 records present. Refer to the screenshot below for visual reference. https://i.sstatic.net/hdaW9.png This is the approac ...

Exploring the World of jQuery Caching and Navigating Through Objects

I'm interested in learning more about jQuery caching and how it can enhance performance. Can you explain how to properly utilize this technique? From what I understand, when using a jQuery selector, you're essentially searching the DOM to create ...

Exporting Textures with Custom Offsets to GLTF from Three.js Scene

UPDATE: I was initially puzzled about exporting to obj and mtl formats, but then I stumbled upon the GLTFExporter.js in three.js which allowed me to successfully extract both the geometry and texture from my project. However, a new challenge arose with t ...

Avoiding the repetition of CSS animations during Gatsby page hydration

I am facing an issue in Gatsby where I have an element with an initial CSS animation. It works perfectly when the static site loads, but after hydration, it keeps repeating. Is there a way to prevent this from happening? Below is my styled components code ...

Unable to clear form using `$setPristine` command

Whenever I try to execute the code below to reset my form, I encounter an error: $scope.resetForm = function () { $scope.testForm.$setPristine(); } Here is the HTML snippet: <form name="testForm" > <label class="it ...

Managing connection pooling in Node.js Express with Oracle (ORA-24418 error: Unable to open additional sessions)

Having some trouble with the Oracle database module you can find here: https://github.com/oracle/node-oracledb/blob/master/doc/api.md My application receives between 300 and 900 hits per hour (typically from about 100 users). It makes multiple $.post requ ...

An issue arises when trying to utilize meta tags in Nuxtjs while incorporating TypeScript into the

When working with Nuxtjs, I encountered an issue regarding my permissionKeys on the page and checking user access in the middleware. Everything runs smoothly when my script language is set to js, but errors arise when set to lang="ts". I tried to find a s ...

The dataset controller in Chart.js returns 'null' when the chart is rendered

Greetings, I must preface this by saying that I am not well-versed in javascript/web development and do not claim to have a strong understanding of the language or its environment. My expertise lies in embedded C/C++ programming, and my foray into learning ...

Creating an array in a Java applet by entering numbers into a textfield

My task involves entering 20 numbers through a text field, then calculating the mean, median, and total using a while loop. I am struggling to store the input numbers in an array. Here is my current code: import java.applet.Applet; import java.awt.Graphi ...

Use the clientID property of the controlname element within JavaScript to access the element using the getElementById method with only

I have a customized compound control that I need to deactivate. This control includes a text field and a calendar component. I want to disable both the image and the text field. Here is how it is identified on the page. The control's name is "datepic ...

Promise of a repeating sequence of serial calls

I am looking to create a recursive serial call to the promise method times, which will return the result of calling the fn function N times and storing the results in an array. To achieve this, I have added a new attribute called results to the times func ...

Invoke a method in an Angular 2 component using an HTML event

Can an angular component method be invoked using an HTML event? <shape onclick="myMethodInParentComponent()" > I am unable to use (click) as shape is not recognized by Angular. Shape also contains several unknown sub elements making it impractical ...

Basic javascript doesn't trigger

Attempting to create a basic AJAX script for testing PHP functionality. However, experiencing issues as the expected output "here" is not appearing due to an error message regarding event.returnValue being deprecated in Chrome. Any insights on what may be ...

Having difficulty accessing information from the parent scope

As I continue to dive into AngularJS, I've encountered some challenges with scopes in my current project. Here is my controller and directive setup: angular.module('myModule', []) .controller('myController', ['$scope', ...

What is the best way to customize fonts for PDFMake in Angular projects?

Recently, I delved into the PDFMake documentation in hopes of creating a document for my Angular application. Along the way, I stumbled upon queries like this one, but unfortunately, found no answers. I am curious if anyone can offer insight or provide a ...