(Definition) What is the proper way to reference a variable inside another variable?

Currently, my project is using inconsistent terminology when referring to variables, and I need to clarify this issue.

Let's take an object defined in this way:

var anObject = {
    a: {
        value1: 1337,
        value2: 69,
        value3: "420 man"
    }
}

I believe that a is a property of the object anObject. But within the context of anObject, how should we describe value1? Is it also considered a "property"?

The reason behind this question is that I am looking to create functions for accessing nested variables within objects. For example:

function getProperty(name) {
    // ...
}

var desiredValue = getProperty("a.value1");

If this inquiry is not suitable for Stack Overflow, please advise on where I can seek assistance. Thank you.

EDIT: My query is not about accessing the nested variable, but rather about the appropriate terminology to use when referring to it.

Given that value1 is a property of a which is a property of anObject, what would we call value1 in relation to anObject? Would it be a "property-property"? I hope this clarifies my question.

Answer №1

Just like how x is an attribute of carObject, value2 is an attribute of x.

To access it, you can simply do:

carObject.x.value2

In a more detailed explanation, this can be broken down into the following code snippet:

const subObject = carObject.x;
const finalResult = subObject.value2;

It's important to understand that in JavaScript, an object is essentially a collection of key-value pairs, similar to a dictionary. Values can be any data type, including other objects, leading to nested structures - such as the one mentioned here.

For the specific function mentioned, all you have to do is split the input string using a designated separator character (like .) and recursively navigate through the object hierarchy until reaching the desired property.

There are already existing libraries on platforms like npm that offer functionality for handling nested keys, such as nested-keys or options within widely used libraries like Lodash. For example, with Lodash's get method:

var obj = { 'x': [{ 'y': { 'z': 5 } }] };

_.get(obj, 'x[0].y.z');
// => 5

_.get(obj, ['x', '0', 'y', 'z']);
// => 5

_.get(obj, 'x.y.z', 'default');
// => 'default'

(This sample code is from the official Lodash documentation for get.)

If you still prefer crafting your own solution, examining the implementation within libraries like Lodash can serve as a helpful reference point.

UPDATE

In reference to your updated query, there isn't a standardized term for this concept. It could be termed as a nested attribute or an attribute of a child object. Describing it straightforwardly as you initially did - where value2 is an attribute of an object which itself is a attribute of carObject - would be technically accurate, even if not the most elegant phrasing, given the absence of a definitive formal designation.

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

Each time my classes are initialized, their components undergo reinitialization

Apologies if the question is not well-formed, I am completely new to working with React. I have been attempting to create a dashboard but encountering issues with my states getting reinitialized. Below is the content of my app.js file. import './inde ...

Error encountered during automatic form submission

My current project involves creating a web notepad that automatically saves changes every minute. The notes are stored in a field called "notas" for each user in the database. Here is some of the code I am using: <html> <head> < ...

c# JavaScriptConverter - understanding the deserialization of custom properties

I'm facing an issue where I have a JSON serialized class that I am trying to deserialize into an object. For example: public class ContentItemViewModel { public string CssClass { get; set; } public MyCustomClass PropertyB { get; set; } } Th ...

Leveraging Angular2's observable stream in combination with *ngFor

Below is the code snippet I am working with: objs = [] getObjs() { let counter = 0 this.myService.getObjs() .map((obj) => { counter = counter > 5 ? 0 : counter; obj.col = counter; counter++; return view ...

Using a string to access a property within a ReactJS object

I am looking to simplify my React Component by referencing a JS object property using a string. This will allow me to remove repetitive conditional statements from my current render function: render() { const { USD, GBP, EUR } = this.props.bpi; ...

Utilize the filtering feature within the Vue select module

I'm struggling to get the select filter to work properly in my Quasar application. When I open the select, there is no list displayed and no value gets selected. Can someone help me understand why it's not working? <q-select v-mo ...

What could be causing passport.authenticate to not be triggered?

After multiple attempts to solve my first question, I am still unable to find the answer. Maybe it's due to being a newbie mistake, but I've exhausted all my efforts. This is how I created the new local strategy for Passport: passport.use(new ...

The http url on an iPad in the src attribute of an HTML 5 video tag is malfunctioning

Having trouble loading a video on iPad using an http URL in the src attribute of an HTML5 video tag. Both static and dynamic approaches have been attempted, but it works fine on web browsers. Here is an example of the code: Static: <!DOCTYPE html ...

Press on the row using jQuery

Instead of using link-button in grid-view to display a popup, I modified the code so that when a user clicks on a row, the popup appears. However, after making this change, nothing happens when I click on a row. Any solutions? $(function () { $('[ ...

Discovering the nearest sibling using jQuery

My HTML code snippet is as follows: $(".remove-post").click((event) => { $(event.target).fadeOut(); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="side-bar"> <b ...

Prevent the execution of a post request function depending on the promise result?

When I handle a POST request in express, I am required to retrieve data from a mongoDB cluster and then respond accordingly based on the retrieved response. app.post('/api/persons', (req, res) => { const data = req.body; if (!data.name || ...

A guide on initiating a get request with URL in React

Utilizing React for the frontend and express for the backend has been my approach. By defining get methods in my express like this:- app.get('/addBill',(req,res)=>{ // --first method res.render("addBill"); }); app.get(&a ...

Tips for utilizing the onClick function in jQuery on an element nested within a div that was dynamically added using jQuery beforehand

I have added some elements inside a div with the class .display_noti like this: $(document).ready(function(){ setTimeout(done,200); }); function done() { setTimeout(updates, 200); // Call updates in 200ms } function updates(){ $.getJSON("notificatio ...

Is sending an AJAX request to a Node.js Express application possible?

Currently, I am attempting to authenticate before utilizing ajax to add data into a database $('#button').click(function () { $.post('/db/', { stuff: { "foo" : "bar"} }, callback, "json"); }); Below is my node.js code: ...

What is the best way to send various parameters to a component using [routerLink] or router.navigate?

My app-routing.module.ts is configured as shown below: const routes: Routes = [ { path: "branches/:branch", component: BranchesComponent }, // ... ]; In addition, in my app.component.html, I have the following code: <li> ...

Looking to incorporate new values without replacing them in react.js and mongoDB

function getFilterQuery() { const completedWorkState = WorkflowStates.findOne({title: 'Completed'}); const inProgressWorkState = WorkflowStates.findOne({title: 'In Progress'}); const identifiedWorkState = WorkflowStates.findOne ...

Unable to execute script tag on PHP page loading

When I make an AJAX request to fetch JavaScript wrapped in <script> tags that needs to be inserted on the current page, how can I ensure that the code executes upon insertion? Here's the snippet I'm using to add the code: function display ...

ways to assign the total of string array elements to the $scope variable

I've been working on binding the total sum of selected checkboxes within a table. I'm almost there, but something isn't quite right. The image above shows 2 checkboxes selected. https://i.sstatic.net/70af2.jpg The code snippet below showcas ...

Developing a dynamic row that automatically scrolls horizontally

What is the best method for creating a div box containing content that automatically slides to the next one, as shown by the arrows in the picture? I know I may need jquery for this, but I'm curious if there's an alternative approach. oi62.tinyp ...

Sequelize.Model not being recognized for imported model

I am encountering an issue while trying to implement a sequelize N:M relation through another table. The error message I keep receiving is as follows: throw new Error(${this.name}.belongsToMany called with something that's not a subclass of Sequelize ...