Understanding JavaScript's JSON Path Variables

I've scoured the internet for solutions to a similar issue but haven't been able to find any helpful information yet.

My current challenge involves accessing a picture path (in JSON format) based on the material type of the selected element. Here is how my code currently looks:

if (globalData.Material.Mat_type == "OSCILLOSCOPE") {                                                         
  var picture = (globalData.Material.Oscilloscope.picture);                     
}
if (globalData.Material.Mat_type == "ALIMENTATION") {                                                         
  var picture = (globalData.Material.Alim.picture);                     
}

This setup isn't optimized, so I'm attempting to refactor it like this:

var mat_type = (globalData.Material.Mat_type);

var picture = (globalData.Material[mat_type].picture);

Unfortunately, this strategy doesn't seem to be working as intended. An exception has been thrown:

TypeError : globalData.Material[mat_type] is undefined.

I've experimented with various approaches already. Do you have any insights or ideas? Thank you!

Answer №1

In my analysis of the character case issue, I have suggested adjusting the value of globalData.Material.Mat_type to potentially resolve it:

var mat_type =
     globalData.Material.Mat_type.charAt(0).toUpperCase() +
     globalData.Material.Mat_type.substr(1).toLowerCase();

However, it's worth noting that this solution may not cover all scenarios. For example, in the case where Mat_type == "ALIMENTATION", the above approach would attempt to access the Alim property of Material instead of

Alimentation</code. In such cases, you can access properties based on a prefix:</p>
   
<p><div>
<div>
<pre class="lang-js"><code>function pictureOf(material) {
  if (!material || !String(material.Mat_type)) {
    return null;
  }
  let mat_type = String(material.Mat_type).toUpperCase();
  for (var propertyName in material) {
    if (mat_type.startsWith(propertyName.toUpperCase())) {
      return material[propertyName].picture || null;
    }
  }
  return null;
}

console.log(pictureOf({
  Mat_type: "OSCILLOSCOPE",
  Oscilloscope: {
    picture: "picture of oscilloscope"
  }
}));

console.log(pictureOf({
  Mat_type: "ALIMENTATION",
  Alim: {
    picture: "picture of alimentation"
  }
}));

Answer №2

Issue Resolved

Peter Wolf was correct! It turned out to be a case-sensitive problem.

I am not sure how to give credit to Peter's insight, my apologies for that.

In any case, I appreciate the help from everyone!

Answer №3

let materialType = (data.Material.type);
if(materialType !== undefined) {
  let picture = (data.Material[materialType].picture)
}

Always make sure to check for the existence of keys before trying to access their values.

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

Oops, it seems like the project is missing a `pages` directory. Please kindly create one in the project root. Thank you!

Initially, my project setup looked like this: public .next src pages components assets next.config.js It was functioning properly, but I made a structural change to the following: public src client next.config.js jsconfig.json pa ...

Adding a <link> tag with a specific onload attribute in the <head> using Next.js

While working on a Next.js project, I am trying to include the following HTML content within the <head>: <link href="..." rel="stylesheet" media="print" onload="this.media='all'" /> The code I ...

Trouble with Updating Div Content?

Within my HTML code, I have included this JavaScript snippet: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script> var auto_refresh = setInterval( function() { $('#loaddiv').fadeOut ...

The problem with document.cookie: Functions properly on localhost but displays as empty when hosted on the web

I have been exploring various resources, but none seem to describe my unique situation. Currently, I am in the process of creating a website using ReactJS for the front-end and NodeJS with Express for the back-end. The production versions are accessible a ...

Discovering a specific JSON object member by its corresponding string value

Let's consider a JSON file with information about books stored in it: { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "autho ...

Can you elaborate on the contrast between React Server Components (RSC) and Server Side Rendering (SSR)?

I'm curious about the differences between RSC in React 18 and SSR in NextJS. Can anyone explain? ...

Utilizing JavaScript to iterate through objects retrieved via Ajax calls

Recently, I've been diving into the world of Javascript and delving deep into AJAX. Utilizing Vanilla JS along with simple AJAX, my current task involves fetching a user object from a URL based on the user's input ID. Despite attempting to use .d ...

Quickest method for sorting an array of objects based on the property of another object's array

Within my code, I have two arrays of objects, both containing a "columnId" property. My goal is to rearrange the first array to match the order of the second. I attempted the following method: filtered = visibleColumns.filter(function(v) { re ...

Examples for Foursquare using asp.net

As someone who is new to JSON, I find myself a bit puzzled. My goal is to utilize userless access for the foursquare api in order to retrieve venue information for a specific location. Can you provide me with a comparable example using .net? ...

typescript error: passing an 'any' type argument to a 'never' type parameter is not allowed

Encountering an error with newUser this.userObj.assigned_to.push(newUser);, receiving argument of type 'any' is not assignable to parameter of type 'never' typescript solution Looking for a way to declare newUser to resolve the error. ...

Are the features of emulation mode in IE11 identical to implementing the meta EmulateIE7 tag?

When using the IE11 browser, I encountered an interesting message on the console: “HTML1122: Internet Explorer is running in Enterprise Mode emulating IE8.” Upon researching this error code on this link, I found out that it is a mode configured by IT ...

One should refrain from loading the API in Angular when there is no data present, by utilizing the global.getData method

Check out this code snippet: loadNextBatch() { console.log('scrolldown'); this.pageIndex = this.pageIndex + 1; this.global.getData(`/conditions/latest?start=${this.pageIndex}&length=${this.pageSize}`) .pipe(take(1)).subscr ...

What is the typical response time for a request using javascript axios?

In my current application, I am fetching data from an API and everything is functioning correctly. However, I am interested in determining the duration of each request in milliseconds. To achieve this, I implemented interceptors using axios. The challenge ...

Exploring PostgreSQL features: JSON vocabulary overview, window functions, and perhaps even recursion?

In my PostgreSQL 9.3 database, I have a "dictionary" containing various terms. I am trying to extract all the terms and organize them into groups of three characters each to display on pages with a maximum of 30 terms per page. The goal is to ensure that n ...

Update the JSON data following deletion

I have received the following JSON data: "memberValidations": [ { "field": "PRIMARY_EMAIL", "errorCode": "com.endeavour.data.validation.PRIMARY_EMAIL", "createdDateTime": null }, ...

Steps for removing a p5.js instance once three.js assets have finished loading

I am trying to implement a preload animation using a p5 sketch while loading a three.js gltf file onto my webpage. The idea is to have the p5 animation play while the heavy gltf file loads in the background. However, I am facing issues with triggering the ...

Angular 12: How to detect when a browser tab is closing and implement a confirmation dialog with MatDialog

I have a scenario where I am checking if the browser tab is closed using the code below. It currently works with windows dialog, but I would like to incorporate MatDialog for confirmation instead. @HostListener('window:beforeunload', ['$eve ...

Tips for creating a Calculator with AngularJS

I am encountering issues while trying to develop a calculator using AngularJS. Below is the HTML code I have written: <!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-com ...

Experiencing a 404 ERROR while attempting to submit an API POST request for a Hubspot form within a Next.js application

Currently, I am in the process of developing a Hubspot email submission form using nextjs and typescript. However, I am encountering a couple of errors that I need help with. The first error pertains to my 'response' constant, which is declared b ...

NodeJS reports an invalid key length, while C# accepts the key length as valid

Currently, I am in the process of converting Rijndael decryption from C# to NodeJS. The Key (or Passphrase) being used is 13 characters long, while the IV used is 17 characters long. Note: The length choice for both Key and IV is beyond my control Disp ...