Is it possible to retrieve an object based on a variable value?

This seems like a simple problem...

I possess an object

const VR03 = {
    name: "Eternal Growth Ring",
    price: "2500"
}

Within a function, I am assigning a string to a variable

function myFunction(){
    let js_type = jQuery('#type').val();
    console.log(js_type); //returns "VR03"
}

Is there a way to retrieve VR03.name using only the js_type variable?

function myFunction(){
    jQuery('h1').text(?);
}

I attempted String(js_type).name but it yields the same result as js_type.name

Answer №1

One method for dynamically searching for an object using a string involves using a separate object as a reference table:

var items = {
    "ID012": {
        name: "Sparkling Star Necklace",
        price: "1200"
    }
}

function findItem() {
    var itemID = jQuery('#itemID').val();
    var item = items[itemID];
    if (item)
        jQuery('h2').text(item.name);
    else
        // Item not found.
}

Answer №2

If you're using a web browser, experiment with the following code:

window[js_type].name

This code accesses the global variable VR03. However, relying on global variables is generally discouraged due to the potential for unexpected behavior.

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

Saving the output of a function in Javascript/NodeJS to a variable

I've been attempting to save the output of a function into a variable, but it's not working as expected. I've exhausted all my ideas and possibilities. Perhaps I'm just making a silly mistake :D I'm working with NodeJS, using expre ...

Animating text with a shake effect using JQuery

I am attempting to create a shake effect on my text input field when validation fails. While I have achieved the shake effect, I am unsure how to customize the default values for direction, distance, and times. Additionally, I believe there is an error i ...

UI and `setState` out of sync

Creating a website with forum-like features, where different forums are displayed using Next.js and include a pagination button for navigating to the next page. Current implementation involves querying data using getServerSideProps on initial page load, f ...

Having issues with AngularJS rzslider failing to dispatch updated slider value

Hello, I am currently using the rzmodule/rzslider in AngularJS. However, after changing the slider to a specific range, the ng-modal is not returning the updated value. It keeps returning the initial value of 10000 that was configured initially. $scope.sl ...

Unable to add files to my JavaScript file

I recently integrated React into an existing project, following the guidelines outlined here: https://reactjs.org/docs/add-react-to-a-website.html. Now, I'm facing an issue where I am unable to import any files (both .js and .css) into my main compone ...

Error: Unable to assign value to property 'src' because it is null

Currently, I am attempting to display a .docx file preview using react-file-viewer <FileViewer fileType={'docx'} filePath={this.state.file} //the path of the url data is stored in this.state.file id="output-frame-id" ...

Is it possible to receive both errors and warnings for the same ESLint rule?

My team is currently in the process of refactoring our codebase, utilizing ESLint to pinpoint any lint errors within our files. Initially, we set high thresholds in one .eslintrc file and have been gradually decreasing these limits as we enhance specific f ...

What is the best way to create a function library that works seamlessly across all of my Vue.js components?

I am currently in the process of developing a financial application using Vue.js and Vuetify. As part of my project, I have created several component files such as Dashboard.vue Cashflow.vue NetWorth.vue stores.js <- Vue Vuex Throughout my development ...

Python's method for passing an array to a Django template

If I had an array in my Python backend and needed to send it to the front end as JSON or a JavaScript array, how could I accomplish this utilizing the Django framework? A possible template implementation is as follows: <script type="text/javascript"&g ...

The live updates for user data in Firestore are not being reflected immediately when using valueChanges

Utilizing Angular and Cloud Firestore for my backend, I have a setup where users can follow or unfollow each other. The issue arises when the button text and list of followers/following do not immediately update on the front end after a successful click ev ...

Struggling to display the Three.js LightMap?

I'm having trouble getting the lightMap to show on my mesh. Here's the code I'm using: loader.load('model.ctm', function (geometry) { var lm = THREE.ImageUtils.loadTexture('lm.jpg'); var m = THREE.ImageUtils.loadT ...

Transform the elements of a tensor in TensorFlow into a standard JavaScript array

Having utilized the outerProduct feature within the TensorFlow.js framework on two 1D arrays (a,b), I am faced with a challenge in obtaining the values of the produced tensor in regular JavaScript format. Despite attempts using .dataSync and Array.from(), ...

Mutex in node.js(javascript) for controlling system-wide resources

Is there a way to implement a System wide mutex in JavaScript that goes beyond the usual mutex concept? I am dealing with multiple instances of a node.js cmd running simultaneously. These instances are accessing the same file for reading and writing, and ...

ReactJS component disappearing behind the Navbar

When using my React app, I have a navigation bar at the top. The Navbar component is called in App.js, and the code snippet below shows how it is implemented. export default function App() { return ( <Router> <Fragment> ...

Creating TypeScript modules for npm

I have been working on creating my first npm module. In the past, when I used TypeScript, I encountered a challenge where many modules lacked definition files. This led me to the decision of developing my module in TypeScript. However, I am struggling to ...

Using an npm package: A step-by-step guide

Recently, I added the following package to my project: https://www.npmjs.com/package/selection-popup I'm curious about how to utilize its features. Can you provide some guidance on using it? ...

Display numerical data at precise locations above an image

Currently, I am working on a project where I am adding multiple marker pins to an image and saving their positions (x and y coordinates) to a database for later use. To see the code I have written so far, you can visit this link: https://jsfiddle.net/at3w ...

How to add suspense and implement lazy loading for a modal using Material-UI

Currently, I am implementing <Suspense /> and lazy() to enhance the performance of my project. While everything seems to be working smoothly, I have observed some minor changes in DOM handling that are causing me slight confusion. Consider this scen ...

The act of transmitting data via a timer using JS WebRTC leads to crashes if the page is reloaded before

In one of my server.js files served by a node, I have written the following code snippet: function multiStep(myConnection, data) { var i=0; var myTimer=setInterval(function() { if (i<data.length){ var element=JSON.string ...

Is it possible to utilize WebAssembly in JavaScript to access the memory of a C struct directly?

Looking at the C code snippet below, there is a struct defined as follows typedef struct { ValueType type; union { bool boolean; double number; Obj* obj; } as; } Value; The ValueType enum used in the struct is defined a ...