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

Converting multiple WordPress plugins into a single JSON option

Having a plugin with numerous options, I am utilizing an angular application on the frontend to display them all. In order to store these options in the database as JSON data, I need to ensure that all 10 options are saved within a single row in the wp_opt ...

When an input value changes in jQuery, the script attempts to locate the parent element and then find the next input. However, in some cases, the value returned

I am currently attempting to retrieve the nearest input field within the same or different class that is located in the subsequent row div section. Unfortunately, I am receiving an 'undefined' response and unable to acquire the desired informatio ...

Tips on parsing JSON data with Python

I am currently working with a module that provides data in the following format: j = ("{u'auth_user': {u'first_name': u'a', u'last_name': u'b', u'uid': u'x', u'timezone_offset&apos ...

Gather data from various textboxes and combine them into a unified string with the help of JavaScript

I am currently facing a challenge where I need to extract the values from multiple textboxes and combine them into a single string. This string will then be sent to my PHP processing page for insertion into a database table. The textboxes mentioned above ...

JavaScript not redirecting to HTML page as expected

I have developed a basic login page that makes an Ajax request to the backend. However, I am experiencing difficulties with redirecting the page upon successful login. The redirect function only seems to work 1 in 15 times, and I'm unsure of the reaso ...

Every time I attempt to send a post request, I receive back only the creation date and the unique objectID

Whenever I send a post request, only the created date and objectID are returned. Whenever I send a post request, only the created date and objectID are returned. This issue persists even after multiple attempts. I attempted to verify it using Postman ...

Transfer JSON data from a web URL straight into couchDB using cURL

Is there a way to directly insert JSON data obtained from a curl -X GET command into a couchDB database? For example, is it possible to achieve the following: >>> curl -X GET -H "some_header" http://some_web_JSON -X POST http://127.0.0.1:port/so ...

What steps can I take to make sure JSON keys containing only digits are treated as Strings instead of Numbers?

Within a JSON String, I have IDs as keys, represented as Strings of numbers, while the values are actual Numbers (Float). The problem arises when parsing this information to obtain an object in Safari 10.1.2... var jsonData = "{\"53352\":0.6, ...

Getting the dimensions of an image when clicking on a link

Trying to retrieve width and height of an image from this link. <a id="CloudThumb_id_1" class="cloud-zoom-gallery" rel="useZoom: 'zoom1', smallImage: 'http://www.example.com/598441_l2.jpg'" onclick="return theFunction();" href="http ...

Communication between child and parent components in Vue.js is an essential feature

Attempting to invoke functions from my component to Vue for the login process. This is the code snippet of my component : Vue.component('auths', { data: function() { return { ip: '', sessiontoken: '' } ...

Should the Express.js router be required directly or stored in a variable before use?

I've been pondering a performance question related to express.js. In my server.js file, I have all the routes defined and the child routes are imported as follows: const ROUTE__FOO = require('./routes/foo') const ROUTE__BAR = require(' ...

Changing the value of an object property (illustrated using a basic linked list)

I am working on a JavaScript Link List implementation as a beginner, and I have written the following code: var LinkList = function () { this.LinkedList = { "Head": {} }; }; LinkList.prototype = { insert: function (element) { var Node = this ...

Display/Conceal content with JQuery on a PHP webpage

I am having trouble with the following code. My intention is to show/hide the content between the #info id when clicking buttons, but nothing seems to be happening. Could you help me identify the issue? echo '<script> $( "#show' . $r ...

Can Masonry.js content be perfectly centered?

I am currently experimenting with creating a layout consisting of one to four variable columns per page using the Masonry plugin. I have been impressed with how it functions so far. However, there is an aggravating gap that persists despite my best effort ...

I'm having trouble pinpointing the cause of the never-ending loop in this React code that is using Material UI grid

There seems to be an issue with infinite looping in this code, and I can't figure out the cause, import React, { useEffect, useState } from 'react'; import VideoCardComponent from './VideoCard'; import Grid from '@mui/material ...

The authService is facing dependency resolution issues with the jwtService, causing a roadblock in the application's functionality

I'm puzzled by the error message I received: [Nest] 1276 - 25/04/2024 19:39:31 ERROR [ExceptionHandler] Nest can't resolve dependencies of the AuthService (?, JwtService). Please make sure that the argument UsersService at index [0] is availab ...

In React, the entire component refreshes every time the modal is opened

<ThemeProvider theme={theme}> <GlobalStyle /> {componentName !== 'questionaire' && componentName !== 'activityResult' && <CardWrapper />} <ErrorModal ...

What is the best way to activate a click event when I set a radio button to checked?

I am facing an issue with an uninitialized property in my app.component.ts: color!:string; I am trying to automatically initialize the color property when a radio button is selected: <div> <input type="radio" name="colors" ( ...

Click to delete the <p> element

For the past few days, I've been struggling with this issue and have tried various approaches to solve it. However, I can't seem to remove the element for some reason. Can anyone offer some insight? My objective is to add the inputted markup on ...

Ways to distinguish between two div elements that have scroll bars and those that do not

I created a div with CSS styling. .comment-list { margin: 20px 0; max-height: 100px; min-height: 100px; overflow-y: scroll; width: 100%; background-color:#000; } Here is the HTML code for the div: <div class="comment-list"> </div> When the ...