Solving a dilemma involving JavaScript functionality and organizing data in a database table

When retrieving data from a database table, I receive values of "yes" or "no" to indicate whether a specific item is available. Instead of simply concatenating the names with the values, I am looking for a way to create a string that lists only the available products by name.

One approach I'm considering involves using a series of if statements to assign each product name to a variable based on its availability status, and then including all the variables in the final string:


var kt; 
if (kitchenTable == yes) kt = "kitchen table"; 
else kt = ""; 

var kc;
if (kitchenCabinet == yes) kc = "kitchen cabinet";
else ka = "";

output = kt + ', ' + kc; 

Since there are approximately 50 items to be considered, I'm exploring more efficient solutions to this problem. One potential option is to modify how the data is stored in the database table so that instead of "yes," the entry would include the actual item name. However, this might not be the best solution overall.

Answer №1

It goes without saying that not all details are disclosed regarding the query method, hence this serves as a conceptual representation of a function mimicking a query operation.

var availableItems = [];

var queryResult = query("living room sofa");
queryResult === "yes" && ( availableItems.push("living room sofa") );

......

var finalOutput = availableItems.join();

Answer №2

If you're looking for a solution, JavaScript has got you covered.

One way to simplify your code and make it more readable is by using an object literal.

Converting server data into true and false values is a common practice for communicating Boolean values, which can be used in the method below:

// Sample server response
var results = {
                    kitchenCabinet: true,
                    kitchenTable: true
}

// Maintain a list of related items
var kitchenProps = { 
                  kitchenCabinet: 'kitchen cabinet',
                  kitchenTable: 'kitchen table'
 }

// Use this function for different categories (e.g., masterBathroomProps...)
function getItemDataIfExists(results, hashTable){
    'use strict';

    var output = 'Your total is: '; 

    for (var item in results) {
        if (!results.hasOwnProperty(item)) return;
        if (results[item]) output += 'A '+hashTable[item]+' ';
    }

    return output;
}


getItemDataIfExists(results, kitchenProps);

Explanation:

This logic iterates through an object with key-value pairs, where keys represent item names and values indicate existence. If a value is true, it retrieves the corresponding property from another object. The key names in both objects must match.

For a live demonstration, check out this link:

http://codepen.io/nicholasabrams/pen/JXXbYz?editors=0010

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

Learn how to use canvas and JavaScript to draw lines that display x and y coordinates on top of the mouse pointer at the same time

Implement a functionality in which lines are drawn while the mouse button is held down and simultaneously display x & y coordinates on top of the mouse pointer during mouse movement using canvas and JavaScript. The issue arises when attempting to draw lin ...

Having issues with passing data to a Modal on eventClick using FullCalendar with ReactJS, receiving a "cannot read property of undefined" error. Any advice on how

My MERN stack application utilizes the FullCalendar plugin, even though I am aware that mixing jQuery with React is not ideal. Unfortunately, I am a novice developer and running behind schedule. The goal is to allow users to click on an event on the calen ...

Reset the AJAX object using jQuery

Currently, my code looks like this: object1 = $.ajax({ .. .. }); If an error occurs, I would like to have the ability to restart the ajax request. For instance, if the user's connection is lost, I want to be able to easily call the same ajax again w ...

Using JavaScript to assess the outcome of a form utilizing an if statement

Trying out a method to assess a result by utilizing an if statement on the form provided below. Upon dividing the 2nd result by the 1st result, an average percentage is calculated. If this percentage is equal to or higher than 55, then the outcome is label ...

What is the best way to modify the views directory for deploying on Vercel?

Currently facing an issue trying to deploy my Express application with EJS template on Vercel. Post deployment, encountering an internal server error along with the following message in the logs: Error: Failed to lookup view "home.ejs" in views directory " ...

When utilizing npm install buefy and npm install font-awesome, there may be an unnecessary display of [email protected] and [email protected] extraneous errors

After installing buefy and font-awesome, I noticed that it is marked as extraneous and the folder appears with an arrow icon but is empty. How can this issue be resolved? For example: +-- <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Combining the contents of one HTML table with Bootstrap styling into another Bootstrap table

Check out the Bootstrap UI I created in the screenshot below: https://i.sstatic.net/NnZzI.png Here's the code. When a user clicks on the accept button in the new orders table, I want 'food 1' to move to the 'accepted' table. M ...

Using PHP to Insert Data into MySQL Database in a Loop

I seem to be approaching this problem in the wrong way. Can anyone provide guidance? My goal is to move all rows with a specific product number from one table to another when it is sold. Thank you in advance. $addinfo1 =""; //Establish a connection ...

Hierarchical configuration selection

Apologies for any confusion earlier. I've received approval from my boss to share this section of the schema. If allowed, I would have included more details in the initial post by posting an image. The configuration schema I'm working with resem ...

Vue JS Spinner that can be used for multiple components within a single page in the same Vue application

Welcome to my Vue.js app. I am looking to add separate spinners inside each component's body instead of loading for the entire app. If there are any other spinner plugins available, feel free to suggest them. CDN links for Vue.js <script type="te ...

JavaScript code altered link to redirect to previous link

I added a date field to my HTML form. <input type="date" name="match_date" id="matchDate" onchange="filterMatchByDate(event)" min="2021-01-01" max="2021-12-31"> There is also an anchor tag ...

Obtain user input and extract the name using jQuery's serialization function

Trying to extract user input from a dynamic form using jquery serialize. The structure of my form is as follows: <form id="lookUpForm"> <input name="q" id="websterInput" /> <button onclick="webster(); return ...

The functionality of array.map appears to be malfunctioning within ReactJS

I'm having trouble mapping my array tabList to the <li> tags that I need. Can anyone help me figure out what I did wrong? import React, { Component } from 'react' // import NeilProfile from './neil-profile.jpg' import Expert ...

Is AJAX/JSON Referencing the Way to Go?

After making good progress in using JavaScript to fill in values, I've hit a roadblock. Despite checking my references, my html table isn't displaying any output. The goal is simple - extract values from a JSON retrieved by an API and insert the ...

Tips for outlining regions on Google Maps

Is there a way to create boundaries on Google Maps based on zip codes or names of areas/cities? Where can we find the coordinates for these boundaries? An example image is provided below. In this image, I have searched for "Ghaziabad" and Google Maps has ...

javascript send variable as a style parameter

screen_w = window.innerWidth; screen_h = window.innerHeight; I am trying to retrieve the dimensions of the window and store them in variables. Is there a way to then use these variables in my CSS styles? For example: img { width: screen_w; height: s ...

Struggling with the functionality of having numerous jQuery UI controls on a single page. Implementing the accordion control in multiple sections

For my current project, I am utilizing the jQuery UI accordion control twice on a single page. The first one functions perfectly fine, but when I attempt to add a second accordion, the original one stops working while the new one works correctly. Does any ...

The ultimate guide to personalizing group titles in Angular UI-Select

Is there a way in Angular ui-select to customize the group label? I want to make it larger than the selection items as shown in the image below. https://i.stack.imgur.com/ofcak.png The list is currently grouped by country, but how can I adjust the size o ...

Tips for translating mesh without using its center point, but instead using its vertices

In my current project, I am utilizing the ThreeJS library. One of the challenges I have encountered involves setting the position of a mesh using mesh.position.set(x,y,z). However, I am interested in moving the mesh to a specific point based on its verti ...

"Add a new record into the MySQL database by selecting the highest value and

This scenario involves two tables being utilized. The objective is to populate table A using the data from table B. However, the desired results are not being achieved as seen below: A mid itemcode seq 1 101 1 1 101 2 1 102 3 2 101 1 2 102 2 B mid it ...