Utilizing JavaScript to retrieve a property from within a method

How can I access a property from inside an object? Manually entering its path allows me to retrieve the property, but not when attempting to do it dynamically.

What am I missing in the code snippet below?

var myApp = {
    cache : {},
    init: function() {
        myApp.cache.akey = 'A value'; // Set the cached value
        myApp.get('cache', 'akey'); 
    },
    get: function(from, key ) {
        console.log(myApp.from.key); // undefined
        console.log(myApp.cache.akey); // A value
    }
};

Answer №1

Your example does not make use of the 'from' and 'key' arguments, as they are not referenced. Instead, the properties are treated as literals.

Consider trying:

myApp[from][key]

Answer №2

The period method of access is straightforward, but if you need to access using a variable as the key, then you should opt for bracket notation:

fetch: function(source, index ) {
    console.log(myApp[source][index]); // In this example, if source holds "memory" and index holds "bkey", it will retrieve myApp.memory.bkey

}

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

The positioning of the JQueryUI menu is experiencing some issues

My goal is to dynamically create menus using JQueryUI menu widgets. Check out this Plunker Example for Dynamic Menu Creation with some issues I am facing an issue where the menu is not positioning itself correctly. It always appears near the bottom of my ...

error: local server did not return any data

I am currently using PHP on a Linux machine. In my HTML code, I have set up an AJAX request to the local Apache server (check http://localhost), with the intention of displaying the data from the server on the screen. However, for some reason, nothing is b ...

Strategies for restricting user input within a datalist

I have a project in which I am creating a webpage that displays a list of flights that can be filtered by destination, origin, price, and more. To achieve this, I have categorized each flight within a div element using its specific properties as classes. F ...

What is the reason for the React component being rendered four times?

My React component is fetching data from Firestore and storing it in the items array. However, I am encountering an issue where the menus variable contains three empty arrays that are being rendered on the page. Initially, I used an async function to fetc ...

Guide on incorporating text onto objects with three.js

I successfully incorporated text into my shirt model using a text geometry. Check out the code below: var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); ctx.font = 'italic 18px Arial'; ctx.te ...

What is the best way to create three buttons for selecting various parameters?

I have a code snippet where I want to assign different parameters to each button when clicked. However, despite my logic, the functionality is not working as expected. Can someone help me with the correct syntax? For example, if I click the "Start (Easy) ...

Vue warning: Do not modify the prop "taskToEdit" directly

I am facing an issue with my props editToTask : app.js:42491 [Vue warn]: To prevent overwriting the value when the parent component re-renders, avoid directly mutating a prop. Instead, use a data or computed property based on the prop's value. Mutate ...

Angular2+ allows users to easily drag and drop an image onto the screen, complete with

Check out this stackblitz link for more details: https://stackblitz.com/edit/angular6-ledera?file=app%2Fapp.component.ts I'm attempting to drag an image from the desktop and drop it directly onto the dropzone div. 1) Obtain a preview of the image 2) ...

Creating unique identifiers in Knockout.js based on text bindings

I am trying to achieve something similar to the code snippet below: <!-- ko foreach: subTopics --> <div id='subtopic-name-here'> <!-- /ko --> Specifically, I want the ID of my div to be set as the name of the corresponding ...

Exploring Javascript through Python using Selenium WebDriver

I am currently attempting to extract the advertisements from Ask.com, which are displayed within an iframe generated by a JavaScript script hosted by Google. Upon manually navigating and inspecting the source code, I can identify the specific element I&ap ...

What is the best way to streamline the if statement in JavaScript?

Here is the given code snippet: public noArtistBeingEdited(): boolean { if (this.isFirstNameBeingEdited()) { return false; } if (this.isLastNameBeingEditable()) { return false; } return true; } What are some ways to ma ...

Having trouble displaying the input upon clicking the icon

Currently, I am honing my skills in vanilla JavaScript by working on a website project. In this project, I have implemented a feature where clicking on a fingerprint icon triggers an input field to appear for the user to enter their password. The code snip ...

Reset the child JSP page to its original appearance

Displayed below is a JSP page: <div id="tabs-7" style="width: 100%;"> <form:form id="deviceForm" name="" modelAttribute="" enctype="multipart/form-data"> <div class="inputWidgetContainer"> <div class="inputWidget"> <table> ...

Using the OR operator in a JSON server

One way to retrieve data from a json-server (simulated server) is by using the following call: http://localhost:3000/posts?title_like=head&comments_like=today When this call is made, records will be returned where the title is similar to "head" AND c ...

Angular - Ensure completion of a function call before continuing with the code execution

I'm currently working on developing a code snippet that checks for potential adverse drug reactions between two medications. Within my checkForClash() function, there is a call to getCollisionsList(), which is responsible for populating the interacti ...

Can anyone point out where the mistake lies in my if statement code?

I've encountered an issue where I send a request to a page and upon receiving the response, which is a string, something goes wrong. Here is the code for the request : jQuery.ajax({ url:'../admin/parsers/check_address.php', meth ...

How can I extract a list of errors from this JSON object in a React.js application?

Is there a way to extract the list of errors from the following JSON object using React js? data = { "container_1587015390439_0001_01_000004": { "ERROR":["20/04/16 05:43:51 ERROR CoarseGrainedExecutorBackend: RECEIVED SIGNAL TERM"] , ...

How can JavaScript determine if this is a legitimate JS class?

I'm currently in the process of converting a React.js project to a next.js project. In my project, there's a file named udf-compatible-datafeed.js. import * as tslib_1 from "tslib"; import { UDFCompatibleDatafeedBase } from "./udf-compatibl ...

What is the reason for Backbone including model details within {model: {model_property: value,...}} when saving a model?

I am currently developing an application using node.js and backbone.js. However, I have encountered an issue where saving a model results in the JSON being nested inside a model dictionary. node = new NodeModel({prop1:"value1", prop2:"value2"}); node.save ...

Obtaining a fresh access token from a refresh token using the googleapis npm library

I've been searching everywhere for an explanation, but I can't seem to find one. The documentation I've read says that refresh tokens are used to obtain new access tokens, but it doesn't explain the mechanics behind it. Normally, I wou ...