To validate any object, ensure that it contains a specific key before retrieving the corresponding value in typescript

When looking at a random object, my goal is to verify that it follows a certain structure.

obj = {WHERE:{antherObject},OPTIONS{anotherObject}}

Once I confirm the object has the key using hasProperty(key), how can I retrieve the value of the key?

I thought about implementing something like this.

validateForm(obj: Object):Object { 

if obj.hasOwnProperty("WHERE") {
//return the value of "WHERE"
}
else{
throw new Error("WHERE isnt a key in this object");}

Answer №1

When it comes to javascript (and typescript), there are a couple of approaches for accessing object properties:

  1. Utilizing dot notation, such as obj.WHERE
  2. Employing bracket notation, like obj['WHERE']

The preferred method is typically using dot notation if you already know the specific key you're searching for. On the other hand, you'll need to leverage bracket notation when dealing with a variable or dynamically generated value as the key.

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

Vue snapshot testing is encountering a failure with the error message "TypeError: Cannot read property of undefined"

Everything seems to be working fine with the component on the page without any errors. Storybook is also functioning well, but the problem lies in the unit test. import { mount } from '../../vue'; import { createLocalVue } from '@vue/test-u ...

After an error occurs, the Node.js Restify code will be executed

Within a Restify route, I have set up a router handler that calls a custom module for error checking. If the code encounters an error condition, it returns next(err) and displays the error message in the browser. However, the code does not stop executing a ...

Vanilla JavaScript: toggling text visibility with pure JS

Recently, I started learning javascript and I am attempting to use vanilla javascript to show and hide text on click. However, I can't seem to figure out what is going wrong. Here is the code snippet I have: Below is the HTML code snippet: <p cla ...

When using html2canvas in Angular, it is not possible to call an expression that does not have a call signature

I'm currently working on integrating the html2canvas library into an Angular 8 project. Despite trying to install the html2canvas types using npm install --save @types/html2canvas, I'm still facing issues with its functionality. Here's how ...

Guide on creating dynamic route paths for includes within a Pug template

Need help creating a dynamic include For example: h1 include path/#{object} or include path/+{object}+{a:true,b:11} Something similar to the above. If anyone knows how to achieve this using Mixins in pug, please provide an example for include. ...

Having trouble with the functionality of Bootstrap's nav-tabs 'show' feature?

I'm having some issues with adding a search box to my glossary. The glossary is created using nested unordered lists (ul) within another ul that has classes of "nav-tabs" and "bootstrap". In the JavaScript code, I am using the following snippet: $j(& ...

Is it possible to automate a query to an API through PHP and store the results on a local drive?

Recently, I created a webpage that fetches data from an API. However, the response time from the server is quite slow, taking around 10-20 seconds to retrieve the information. To mitigate cross-domain issues, I have set up a PHP proxy for the JavaScript re ...

Looking for a particular root node in a tree structure?

I am currently working on converting docx files to xml and using DOM to locate the parent node of a specific element. For instance <chapter> <title> <label>Chapter 1 </label> </title> ...

Express receiving undefined data in Ajax POST request

I'm currently facing an issue with sending data to be parsed. The client-side script I have is as follows: function addURL(link) { console.log("Adding url..."); $.ajax({ type: "POST", url: location.protocol + "/ ...

Change the behavior of JavaScript so that it executes when clicked, not when the

This script is currently set to run when the page loads: <script language="JavaScript"> j=parseInt(Math.random()*ranobjList.length); j=(isNaN(j))?0:j; document.write(unescape(ranobjList[j])); </script> Is there a way I can mak ...

Information is not appearing in the table

I'm having trouble displaying data in a table format. The issue arises when I try to fetch data from a JSON file using a custom service. The fetched data is then inserted into the $rootScope object. However, when I preview the view, it appears blank ...

Align a collection of images in a grid format on the center of the page with

I am trying to center a div that contains multiple 145px X 145px thumbnail images without setting a fixed width. The goal is to have as many images in each row as the browser window can fit. However, I want to keep the images left-aligned within the center ...

Interactive PDFs that launch a new browser tab rather than automatically downloading

I am facing an issue with my web API that is returning a JSReport as an encoded byte array. Despite multiple attempts to read the byte array, I keep encountering either a black screen or an error message indicating "failed to download PDF". Interestingly, ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

Obtaining JSON Data Using WinJS.xhr():

I'm encountering difficulties with retrieving chat messages using winjs.xhr: function getMessage() { var time = MESSAGE_RETURNED.unixtime; if (time == 0) { time= window.parent.SESSION.unixtime; } WinJS.x ...

WebStorm is not implementing the exclude option as specified in the tsconfig.json file

Is there a way to exclude a directory from TypeScript compilation in WebStorm? Despite specifying the exclusion in the tsconfig.json file, it seems that WebStorm doesn't respect the setting and compiles everything in the root directory. However, runn ...

Ways to initiate state transition from child component to parent component using React Hooks?

In the parent component, I have the following: const [updateQuantity, quantity] = useState(1); const handleChangeQuantity = e => { console.log(e.target.value); console.log("TEST"); updateQuantity(e.target.value); }; I the ...

typescript: Imported modules in typescript are not functioning

I'm facing an issue where I installed the 'web-request' module but unable to get it working properly. Here is my code: npm install web-request After installation, I imported and used it in my class: import * as WebRequest from 'web-r ...

Show the result of file upload, whether it was successful or not, using ReactJS

I need to implement an Ajax call for uploading a file to the server. I want to display success and failure messages based on the outcome of the file upload process. $.ajax({ url: "https:my_url", data: {my data: my_data}, method : "POST", success: ...

I'm experiencing an issue with my Next.js Airbnb-inspired platform where I am unable to save a listing to my favorites

While working on my Next.js Airbnb clone project, I encountered an issue with adding a Listing to favorites. The heart button component's color does not change when clicked, despite receiving a success response. Moreover, the addition to favorites is ...