Invoke a method within an object using dynamic brackets

let obj = {
    sub: {
        myFunc: function() {
            console.log('check');
        }
    }
}

let callFunction = 'sub.myFunc'; // Can anyone help me figure out why this doesn't work correctly?

obj[callFunction](); // This works fine, but not with 'sub.myFunc'
obj.sub.myFunc(); // This one works as expected.

I'm looking for a solution that will work generically. Any suggestions on why 'sub.myFunc' is not working? Is there a workaround to make it function properly?

Answer №1

Using the . symbol in JavaScript is allowed within property names when enclosed in quotes.

Here's what this means for you:

  • myObject["sub.myFunction"] - searches for a property called sub.myFunction within myObject, not within a sub-property named myFunction on myObject.

  • myObject.sub.myFunction - without quotes around the ., it acts as a property accessor. This way, it looks for a property named myFunction within the sub property of myObject.

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

Ways to retrieve every CSS style attribute using the class name and locate a specific class within the stylesheets

Is there a way to retrieve all CSS properties for each class that matches a specific element? I have the class names of my element from this.className How can I go about getting all the CSS styles for each class name? Should I compare or search within t ...

Mastering the Art of Unit Testing JavaScript Asynchronous Code with Jasmine Mocking

Hello, I recently started learning JS and encountered a problem while testing asynchronous methods with jasmine mocking. Below is the code snippet I am trying to test: test.factory('service', ['$http', '$q', function($http, ...

Obtaining the identifier of the grandparent element that is of the "

I'm working on a project where I have a dynamic element called .courseBox. It's an <li> element that will be placed within a <ul> container. Each .courseBox has a red "x" button that, when clicked, removes it from the <ul>. Here ...

Modifying the URL in JavaScript code and incorporating an additional parameter

Here is a mysql query I am working with: $colname_profile = "-1"; if (isset($_GET['user'])) { $colname_profile = $_GET['user']; } mysql_select_db($database_conn, $conn); $query_profile = sprintf("SELECT * FROM users WHERE user_id = % ...

Transferring data to a child component through Route parameters

Although I have come across numerous questions and answers related to my query, I still seem unable to implement the solutions correctly. Every time I try, I end up with an 'undefined' error in my props. Let's take a look at my parent compo ...

Guide on incorporating data from JSON into a table with JavaScript

Following a tutorial from this source, I am working on creating a real-time table using PHP and AJAX. The PHP file sends back JSON-formatted values: { "retcode" : "0 Done", "trans_id" : "187472", "answer" : [ { "Country" : "US", "Digits" : "5", "Datetime ...

What is the most optimal jQuery code to use?

Just wondering, which of the following code snippets is more efficient (or if neither, what would be the best way to approach this)? Background - I am working on creating a small image carousel and the code in question pertains to the controls (previous, ...

Build a dynamic checkbox list using DOM manipulation in JavaScript, populating it with values from an array

I am looking to create a checkbox list in JavaScript populated with names of animals from an array, and then display them in HTML. Here is my attempt at the code: var animalArrayLength = animals.length; for (var i= 0; pos < tamanhoArrayDiagnosticos; ...

Feature exclusively displays malfunctioning image URLs for the web browser

Hello everyone! I've been diving into learning JavaScript and recently attempted to create a function that randomly selects an image from an array and displays it on the browser. Unfortunately, despite my efforts, all I see are broken link images. Her ...

Why isn't Gzip compression working in webpack? What am I missing?

After comparing the compression results of manual webpack configuration and create-react-app for the same application, it became clear that create-react-app utilizes gzip compression, resulting in a significantly smaller final bundle size compared to manua ...

Is it possible to develop a web API using express.js without the need to have node.js installed?

As I work on developing my portfolio website, I've run into the challenge of hosting restrictions that prevent me from utilizing Node.js. While I understand that Angular can be used on any web server, I'm curious if it's possible to leverag ...

Is it possible for Angular to retrieve information from one JSON file but not another?

After updating the names in the code to reflect the current ones, I would greatly appreciate any help or suggestions! The json file has been provided, so there's not much additional setup required. Just a heads up: I haven't created a service fi ...

Database Submission of Newsletter Information

I recently grabbed the following code snippet from a YouTube tutorial (shoutout to pbj746). Everything appears to be functioning correctly except for one crucial issue - the submitted data isn't showing up in the database! I've thoroughly checked ...

Guidance on editing list items individually using jQuery from separate input fields

Working with li presents some challenges for me. On my webpage, I have an input field that dynamically adds values to a list. However, the function to edit these values is not working properly. After editing an li element, it deletes all classes and span ...

Cross-Domain Communication with XMLHttpRequest

I am facing an issue with the code snippet below: console.log(1); var xhr = new XMLHttpRequest(); xhr.open('POST', 'http://anothersite.com/deal-with-data.php'); xhr.setRequestHeader('Content-typ ...

Unusual Error Encountered in Node.js

Currently, I am working my way through a JavaScript textbook and practicing by running code samples using Node.js. I have been creating files and then executing them with the command node file.js. Typically, I always include semicolons when writing JavaSc ...

Error message: The property '__isVuelidateAsyncVm' cannot be read because it is undefined

I'm encountering an issue with the code I have in this codesandbox link. The code features a form with validation and a disabled "Calculate" button that should only become enabled when all fields are valid. However, I'm receiving the error messag ...

Automatically scroll the chat box to the bottom

I came across a solution on Stackoverflow, but unfortunately, I am having trouble getting it to work properly. ... <div class="panel-body"> <ul id="mtchat" class="chat"> </ul> </div> ... The issue lies in the JavaScript t ...

Best practice for detecting external modifications to an ngModel within a directive

I've been working on creating a directive that can take input from two sources and merge them into one. To achieve this, I'm monitoring changes in both inputs and updating the combined value in the ngModel of my directive. However, there's ...

The modal window obstructs my view on the screen

You are working with a modal form that triggers a POST method in your controller https://i.sstatic.net/0vbOy.png Here is the view code: <div class="modal fade" id="agregarProducto"> <div class="modal-dialog" role="document"> < ...