Do you think there is a more optimal approach to writing if (argList[foo] === "bar" || argList === "bar")?

I have an if statement :

if (argList["foo"] === "bar" || argList === "bar"){
    // some code
}

I am curious if there is a concise or more elegant way to express this condition.

The reason behind writing this statement is that I have two functions: startTool(argList) and startCreate(argList).

mod.zsh_apiStartTool = function(argList, callback) {

        // some code
if (argList["tool"] === "measure" || argList === "measure"){
//some code to start the tool
}
if (argList["tool"] === "scanning"|| argList === "scanning"){
// some code to start the tool
}
ZSH_JS_API_ERROR(callback);
return;
}

mod.zsh_apiStartCreate = function(argList, callback) {

        // some code
if (argList["tool"] === "measure"){
mod.zsh_apiStartTool("measure")
}
if (argList["tool"] === "scanning"){
mod.zsh_apiStartTool("scanning");
}
ZSH_JS_API_ERROR(callback);
return;
}

Hence, when I call startTool from startCreate, my variable will not be argList["foo"] === "bar" but rather argList === "bar"

Answer №1

If you want to ensure that a property exists, I believe it is better to utilize a helper function such as:

  • using the elvis operator in TypeScript
  • Using Lodash's _.get() method

    if (_.get(argList, "foo") === "bar" || argList === "bar"){
               // some code
       }

The issue becomes critical only when attempting to access a nested level like argList["foo"]["bar"]

To Use JSON.stringify Method

Another approach is to stringify the object and then search for the value within it, especially if you are certain that "bar" is a unique value in your object (meaning there are no other properties holding the same value in argList):

JSON.stringify(argListObj).includes("bar")

const argListObj = { foo: "bar" };
const argListString = "bar";
console.log(JSON.stringify(argListObj).includes("bar"));
console.log(JSON.stringify(argListString).includes("bar"));

// Console logs true, true

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

Issue encountered during the creation of a Nuxt3 project. The download of the template from the registry was

Trying to create a new Nuxt 3 project using the command below: npx nuxi init nuxt-app The following error message is displayed: ERROR (node:1752) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time ...

Can you help me figure out how to retrieve the index of a CSS element during a 'click' event?

I have a collection of images all tagged with the class thumb. When a user clicks on one of these images, I need to determine which image was clicked within the array of thumbs. Essentially, I am looking for the index of the clicked image within the thumbs ...

convert and transform XML data into JSON format

I have been working with nodejs-expressjs and I received a response in raw XML format. My goal is to convert this raw XML into either a JavaScript array or a JSON array so that I can extract the domain name along with its status. I want to display this inf ...

What is the best way to design a Global Navigation menu for websites?

For example, I am looking to integrate a Navigation menu into my website using just one file. I have considered using PHP or creating an HTML frame, but I am wondering what the current industry standard is for professionals. Any insights? ...

Sequelize synchronization does not generate the database table

I am currently working on a project with the following directory structure: ├── index.ts ├── package.json ├── package-lock.json ├── src │ ├── controllers │ ├── models │ │ └── repository.ts │ ├ ...

What is the best way to show an error message on a field when using a custom form validator?

In my JavaScript code, I have created a form validator that is capable of validating different input fields based on specific attributes. However, I need assistance with implementing error handling and scrolling to the erroneous field. For each <input& ...

Using a Javascript array within a Bootstrap carousel allows for dynamic content to

I am looking to incorporate my javascript array into a bootstrap carousel so that the carousel can display all the elements from the array and determine which picture should be shown based on the data. I also want it to display the title, subtitle, and alt ...

The gear icon in the video player is not showing up when I try to change the

I am currently trying to implement a feature that allows users to select the quality of the video. I am using videojs along with the videojs-quality-selector plugin, but even though the video runs successfully, the option to choose the quality is not appea ...

Using Javascript or jQuery to Enhance the Appearance of Text on a Website

Is there a way to automatically apply styling to specific phrases on our website by searching for instances of those phrases? For example: <div> This is what you get from <span class="comp">Company Name</span>. We do all kin ...

Why is it that when I use XMLHttpRequest for a menu and request a page with HTML that contains JavaScript, nothing happens?

Below is the code snippet I'm using for a menu in a webpage I am currently developing. In some cases, the page I want to request contains JavaScript, but when the requested page is loaded into the actual page, the script does not run. //Ajax menu all ...

Tips for properly updating the shadow when modifying the vertices of custom geometry in A-Frame/three.js

I've developed a custom component in a-frame that generates a unique geometry. I'm using the tick function to animate the update of the geometry's vertices successfully. However, the shadow on the geometry doesn't seem to update accordi ...

Error: Interface declaration for _.split is missing in the Lodash.d.ts file

For my current typescript project that heavily relies on Lodash with lodash.d.ts, I've encountered an issue with the _.split function not being implemented yet. It's listed under the 'Later' section in the .ts file. I need to find a wo ...

A method of iteration that allows us to traverse through an object, regardless of whether it contains a single item or an array of items, is known as dynamic looping

I am dealing with a JSON output that can have different types of data: There may be an array of objects like this: var data = { "EARNINGS": [ { "PAYMENT": "1923.08", ...

Creating a progress bar feature using local storage in JavaScript

Is there a way to retain the progress of the countdown timer with a progress bar on page reload? Here is an example of what I am trying to achieve: https://codepen.io/Rudchyk/pen/qNOEGj <div id="progressBar"> <div class=& ...

Arranging by upcoming birthday dates

Creating a birthday reminder app has been my latest project, where I store names and birthdays in JSON format. My goal is to display the names sorted based on whose birthday is approaching next. Initially, I considered calculating the time until each pers ...

Is it possible for hooks to be invoked within nested functions?

It's fascinating how useState works seamlessly inside a regular function like regfunc in this React component. One would expect an error to be thrown, but surprisingly it isn't. import { useState } from "react"; export function App() { ...

Transitioning from a fixed position to absolute in CSS3

Sticky Logo Element In my project, I implemented a logo element that is positioned absolutely within the document. As the user scrolls, the logo sticks to the top of the window with a fixed position (you can view an example here: https://jsfiddle.net/swzb ...

Creating a custom JSON structure in React.js to calculate and display monthly amounts

I retrieved data from my API with the following structure: [{…}, {…}, {…}, {…}, {…}] Each object contains detailed information like this: { date: "2018-01-01" import: 1 }, { date: "2018-03-03" import: "10" }, { date: "2018-03-20" impor ...

When attempting to utilize useReducer hooks in React, I am encountering an issue

this is my unique code snippet import React, {createContext, useContext, useReducer } from 'react'; // defining the data layer export const StateContext = createContext(); // creating a provider export const StateProvider = ({ reducer, initi ...

Grunt is unable to handle the lesscss file

I'm in the process of combining a group of .less files into one large .less file, and then converting it into a single .css file using Grunt's grunt-contrib-less module. module.exports = function(grunt) { require('load-grunt-tasks&apos ...