What is the process for retrieving an object's attribute as a variable?

I am dealing with two distinct objects:

object1={
   type: 'obj1',
   nName: 'nName'
}

object2={
   type: 'obj2',
   pName: 'pName'
}

Within my JavaScript code, I have:

object=GET_OBJECT();

The GET_OBJECT() method will return either object1 or object2. My goal is to access the name attribute of the object, which could be either nName or pName.

I have a method in place to retrieve the name (pName or nName) of the returned object:

function getName(Object, name){
      return object.name;
}

I want the name to be a variable, allowing me to access either pName or nName in a flexible manner:

object=GET_OBJECT();

var name='';

if(object.type=='obj1')
   name='nName';
else
   name='pName';

var finalName=getName(object, name);

Unfortunately, it appears as though this setup may not work as intended, since in:

function getName(Object, name){
          return object.name;
    }

Is there a way in JavaScript to access an attribute as a variable?

Answer №1

Here's a suggestion:

function fetchName(obj, key) {
    return obj[key];
}

Answer №2

I often ponder why people offer solutions instead of sharing knowledge. Without understanding the underlying concepts, the asker may continue to make the same errors repeatedly.

The original code relies on a function to fetch an attribute. It assumes that the parameter can be used to call the attribute. Put simply, it uses Dot notation, which requires a valid JavaScript identifier. When using Dot notation, the word after the dot signifies the pointer to the content. As a result, the function getName always attempts to access the attribute name, which may not be defined.

The provided solution utilizes Bracket notation. This method uses the parameter content (even if it doesn't exist) as an identifier and then resolves the content, allowing for successful execution.

While Dot notation offers speed and readability, it is recommended when both options are applicable. Bracket notation is preferable for dynamic resolution at runtime. This is especially useful when defining internal setters and getters. The following code snippet employs bracket notation to ensure that utilizing the identifier via dot notation will trigger the specified functions.

function myClass(){
        //setX and getX functions should be defined prior to this code
        this.__defineSetter__("x", this.setX);    
        this.__defineGetter__("x", this.getX); 
        //Alternatively, Object.defineProperty can be used as well
};

var tObject = new myClass();
tObject.x = 10; //Calling the getter function

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

What is the main file that vue-cli-service utilizes for entry?

Interested in a project utilizing vue, webpack, babel, npm? You can launch it with npm run server. While exploring how this command functions, I came across vue-cli-service serve in the package.json file. But how exactly does vue-cli-service initialize ...

jQuery custom slider with advanced previous and next navigation capability for jumping multiple steps

I am currently learning jQuery and programming in general. Instead of using a pre-built plug-in, I decided to create my own image slider/cycle from scratch to keep the code concise and improve my skills. My function goes through each li item, adding a &ap ...

Issue encountered while attempting to remove a row from a table (JavaScript)

I'm encountering an error when attempting to delete a table row: "Uncaught ReferenceError: remTable is not defined index.html:1:1". When I inspect index.html to identify the issue, I find this: remTable(this) This is my code: const transact ...

Unraveling Vue Async Components - Harnessing the power of emitted events to resolve

I am looking to create a Vue async component that stays in a loading state until a custom event is triggered. This means it will render a specified loading component until the event occurs. Here's an example of how I want it to work: const AsyncComp ...

The deployment of the next.js error on Vercel was successful ✓ All five static pages were generated without any issues. However, there was an error encountered during the export process specifically in the

I'm having trouble deploying a next.js + mongodb project to Vercel. Every time I try, I encounter this error: Error occurred prerendering page "/products". Read more: https://nextjs.org/docs/messages/prerender-error SyntaxError: Unexpected t ...

How can I obtain the true client IP address using Nginx?

I have a straightforward express app that has been containerized using Docker. You can find the repository here. In this setup, I utilized nginx as a reverse proxy. When accessing http://45.33.97.232:3000, it displays the actual server IP. However, if I v ...

What is the best way to display the value of a PHP variable in a JavaScript pop-up window?

Here are the scripts I have. A user will input a numerical value like 123 as a parameter in the URL, and the application will retrieve that value from MySQL and display it in the textarea. For example, if you enter "example.com/index.php?id=123" in the UR ...

The Google Books API initially displays only 10 results. To ensure that all results are shown, we can implement iteration to increment the startIndex until all results have

function bookSearch() { var search = document.getElementById('search').value document.getElementById('results').innerHTML = "" console.log(search) var startIndex = I have a requirement to continuously make Ajax calls ...

What's the reason my JavaScript isn't functioning properly?

Brand new to coding and I'm delving into the world of Javascript for the first time. In my code, there's a checkbox nestled within an HTML table (as shown below). <td><input type="checkbox" id="check1"/> <label th:text="${item.co ...

Finding the offsetWidth (or similar measurement) for a list item (LI) element

Can jQuery be used to determine the width of an element? alert($("#theList li:eq(0)").offsetWidth); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ol id="theList"> <li>The quick brown ...

What is preventing my Button's onClick() method from being effective?

Below is a snippet of my HTML layout using the sciter framework: <div id="volume_micphone_slider" style="z-index:1;"> <input id="volume_slider" class="volume_slider" type="vslider" name="p1c" max="100" value="20" buddy="p1c-buddy" /> < ...

Guide on tallying a unique value of a chosen option within a table using jQuery

I have select elements in my table. I am trying to determine if any of the selected options in those select elements have the value of optional. If any of the select elements has optional selected, then I want to display a text field below it. However, I a ...

When the C# method is executed, jQuery is reset

One feature I have on my website is a "newsletter" widget that expands when the user clicks a button. Inside the expanded section, there is an input box for email address and a submit button. The code behind this functionality verifies the email format and ...

The POST Method is failing to transmit all the necessary data

I recently started a new project using angular, node, express, and postgresql/sequelize. It's been an exciting learning experience, but I've encountered some challenges. Specifically, I'm having trouble setting up an update route for a model ...

What is the meaning of the term writeHead?

Upon reviewing a GroupMe bot template in nodejs, I noticed a common occurrence of the function call res.writeHead(200);. What is the typical purpose of writeHead(200)? Is it a shorthand for "write header"? ...

The attempt to execute 'removeChild' on 'Node' was unsuccessful because parameter 1 is not the correct type. Although it did remove the elements from the DOM, it only did so once

It's quite a challenge I'm facing!!! Although there have been similar questions asked before, they were all for specific scenarios. I am currently developing a tictactoe game using the module design pattern. The function below helps me create tw ...

What is the process for updating the URL for specific functions within $resource in Angular?

Check out this code snippet: angular.module('app.posts.services', []).factory('Post', ['$resource', 'API_ENDPOINT', ($resource, API_ENDPOINT) => $resource(API_ENDPOINT, { id: '@id' }, { updat ...

What are the steps to transform my database object into the Material UI Table structure?

I have a MongoDB data array of objects stored in products. The material design format for creating data rows is as follows: const rows = [ createData('Rice', 305, 3.7, 67, 4.3), createData('Beans', 452, 25.0, 51, 4.9), createData ...

Using AngularJS to send a post request with cherrypy

I am facing an issue with posting events into a CherryPy small application that responds to GET/POST requests. When attempting to do so using AngularJS, nothing gets posted. I'm unsure if the problem lies with AngularJS or CherryPy (CP). Cross-domain ...

What is the best way to continuously compare two date variables every minute using Javascript?

In my script, I have two date variables - one representing the current time and the other two minutes later. My goal is to compare both values every minute and trigger a function when the current time is greater than or equal to the latter time. Unfortun ...