JavaScript tutorial: Removing spaces in column names and creating case-insensitive queries

This morning, I encountered an issue while working on a web app that I am currently developing.

The app is designed to read data from an excel file and import it into a SQL table.

During the basic validation process, I noticed that the column headers in these excel files sometimes have slight variations. Unfortunately, there is no consistency in their naming convention and I do not have the authority to address this problem.

For instance, here is a sample check:

xdata['Meeting ID'] === undefined

Below are different permutations of how the column header may appear:

Meeting ID MeetingID MeetingiD MeetingId

My question is whether there is a method to remove spaces in the column header names and make them case insensitive?

I have searched online for potential solutions, but most of what I found addresses the column values rather than the header itself. It's possible that my search terms are not accurate.

If anyone has an example or suggestion on how to tackle this issue, I would greatly appreciate your input.

Thank you, Erasmo

UPDATE

After trying one of the suggested solutions, I encountered an error:

https://i.sstatic.net/xlmvS.png

https://i.sstatic.net/6XUh2.png

Answer №1

One way to determine if an object is a string or not is by using the typeof operator. Give it a shot with this example:

normalizedColumnName = typeof data['Meeting'] === 'string' ? data['Meeting'].toLowerCase().replace(" ", "");

Answer №2

Could you please verify if the string begins with the word "Meeting"?

let check = str.startsWith("Meeting");

if(check === true) {
name = "Meeting ID"
}

Afterwards, assign it to the name variable.

xdata[name]

Answer №3

The process of transforming input into a standardized output is known as "normalization". This can be achieved by coercing the input data to adhere to a specific format.

One way to normalize data is demonstrated in the following simple example:

normalizedColumnName = originalColumnName.toLowerCase().replace(" ", "")

An updated example showcasing normalization is provided below:

xData = {
  "Meeting ID": [1,2,3],
  "Something Else": [3,4,5],
}
normalizedXData = {}
Object.keys(xData).map(function(columnName) {
  normalizedXData[ columnName.toLowerCase().replace(" ", "") ] = xData[columnName]
})

// normalizedXData === { meetingid: [ 1, 2, 3 ], somethingelse: [ 3, 4, 5 ] }

To enhance readability and compatibility with various browsers, consider using "in" instead of comparing to undefined when checking for a specific key in an object:

if (!("meetingid" in normalizedXData)) {
    console.log("your error message")
}

It's important to note that comparing to undefined directly can be unreliable, particularly with older browser versions.

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

At what point in time does the LoadingFrameComplete event in Awesomium typically happen?

According to the documentation from Awesomium, the event WebView.LoadingFrameComplete is triggered when a frame finishes loading. This description seems somewhat ambiguous. Does this event coincide with the JavaScript load event of the window? Or perhap ...

Understanding variable scopes in the success callback function of a JQuery post request

I am encountering an issue with passing the AJAX success array from one function to another. It seems that I am unable to transfer the data stored in a variable within the success section of the AJAX function to the parent function for return. I tried to ...

Issue with form action redirection on Node JS Express server not functioning correctly

My EJS application involves using jQuery in the JavaScript code to fetch JSON data from the Google Custom Search API. The app then uses the GET method to navigate to /search, passing the query as the attribute for q. Here's an example of the form&apos ...

What is the best way to invoke a controller method using jQuery within a cshtml file?

I am working on a project where I need to add user information to the database by calling a function in my controller class. The user's information is entered through a form created in a .cshtml file that interacts with an external JavaScript file. Is ...

Can the background color of HTML header text be altered using JavaScript in JQGRID?

Can the background color of HTML header text be modified using JavaScript? Updated: Oops, I forgot to mention that it is for the header text in jqGrid. My apologies for that oversight. ...

Using the <object> tag in AngularJS partials for improved functionality

Trying to incorporate the <\object> tag or <\iframe> within a partial HTML file and then include that HTML in another page using ng-include. Here is my attempt: <div class="container"> <!-- This section doesn't displ ...

What is the process for creating a button that can sort an array and count its elements?

I am having trouble creating a code that can sort products into alphabetical order and then count the number of items in the list within the same program. I have managed to write separate programs that achieve each of these tasks individually, but when I ...

Encountering issues with the Sequelize Model.prototype.(customFunction) feature malfunctioning

While attempting to define a customFunction within the Sequelize model, I encountered an error: TypeError: user.getJWT is not a function at User.create.then (/projects/test/a/app/controllers/UserController.js:22:29) Below is the code snippet from ...

Simple steps to convert Redux state to Redux Persist with the help of 'combineReducers' function

I'm facing a challenge trying to implement Redux-Persist with my Redux state, particularly because I am using combineReducers. Here is the structure of my store: import { createStore, combineReducers } from 'redux' import { usersReducer } fr ...

Angular ui-router redirection without altering the ui-view contents

Here's the code snippet from my app.js: // Setting up states using $stateProvider $stateProvider .state('/', { url: "/", views: { "top": { temp ...

What causes the Vue.http configuration for vue-resource to be disregarded?

I am currently utilizing Vue.js 2.3.3, Vue Resource 1.3.3, and Vue Router 2.5.3 in my project while trying to configure Vue-Auth. Unfortunately, I keep encountering a console error message that reads auth.js?b7de:487 Error (@websanova/vue-auth): vue-resour ...

The V-if condition is specifically tailored for a single line or link

I am attempting to conceal a link ("myprofile") beneath an image in VUE.JS when the if-statement is not met. However, when I insert the v-if inside the vue-router or div tag, the entire image/div-tag becomes hidden. How can I implement an if-statement that ...

Stop Chrome from automatically scrolling to the top of the page when making changes to the DOM

Currently utilizing Action Cable to create a discussion room where users can exchange questions. Upon posting a question, all participants within the room are supposed to see it. Nonetheless, I've encountered an odd issue specifically on Chrome: whene ...

Tips for accessing req.fields variables while utilizing Express-Formidable

For some reason, I am encountering difficulties when trying to access variables parsed within req.fields using Express-Formidable. Upon executing a console.log() of req.fields, the output is as follows: { 'registration[username]': '1', ...

What is the best way to deliver client/index.html using server/app.js?

Here is my current file structure: - simulated-selves - client - index.html - server - app.js The goal is to serve the user index.html when they visit the / route. // server/app.js app.get('/', function(req, res) { res.sendFile( ...

Saving JSON data into an HTML element using Handlebars templating

Is there a way to save the entire JSON object within an HTML element as a data attribute? let a = {name : "sample", age : "34"} $.find('#someDiv').data('adata', a); Is it possible to achieve the same result using Handlebars when creat ...

The pop-up menu appears in a location different from where the anchor element is positioned

Having an issue with the menu placement when clicking on an Avatar. The menu is appearing in the wrong position: The avatar button "OB" on the right side is where the issue occurs. No console errors present and inspecting the Popover element shows that it ...

A guide on linking an object in strapi V4 to a React app

Recently in strapi v4, there was a change in the response API structure from an array to an object. When analyzing the response using Postman on my local strapi API and converting it into raw format with stringify, I noticed that the API response consists ...

Center a grid of cards on the page while keeping them aligned to the left

I have a grid of cards that I need to align in the center of the page and left within the grid, adjusting responsively to different screen sizes. For example, if there are 10 cards and only 4 can fit on a row due to screen size constraints, the first two ...

Click on a div to smoothly scroll to the top, then automatically scroll to the bottom if already at the top position

I've implemented a JQuery code on my website that allows the page to scroll to the top when clicking on a div with the class of .bottom. The code is working perfectly fine, here it is: function scrollToTop(){ $('.bottom').click(function ...