Accessing a property of an object through a different property

I have structured my JavaScript file using objects and I am trying to assign one property (which is an array) to another property:

AvGen = {

    theBody: {
        bodies: [
            fooObj,
            foo2Obj,   // <--- need to move this property...
            foo3Obj
        ],
        bodyColor: '#DB6EDB',
        currBodyNr: 1,
        currBodyObj: AvGen.theBody.bodies[1]    // <--- ...to this property

// ... rest of the code

However, I keep getting an error message that says:

Uncaught ReferenceError: AvGen is not defined

If I remove 'AvGen' then it complains that 'theBody' is not defined. What should I do to make this work?

Answer №1

If you're working with modern browsers, consider using a getter:

AvGen = {

    theBody: {
        bodies: [
            1,
            2,
            3
        ],
        bodyColor: '#DB6EDB',
        currBodyNr: 1,
        get currBodyObj() {
           return AvGen.theBody.bodies[AvGen.theBody.currBodyNr];
        }
    }
}

console.log(AvGen.theBody.currBodyObj); //2

FIDDLE

Alternatively, you can opt for a method instead of a property:

currBodyNr: 1,
currBodyObj: function() {
   return AvGen.theBody.bodies[AvGen.theBody.currBodyNr];
}

//...

console.log(AvGen.theBody.currBodyObj()); //2

Answer №2

The first step is to initialize the AvGen object and set its values based on the bodies parameter. Next, you can assign the desired value to this.currBodyObj using a function.

Answer №3

Avgen is not yet initialized on that specific line of code. To fix this, you should follow these steps:

AvGen = {};
AvGen.theBody = {};
AvGen.theBody.bodies = [fooObj, foo2Obj, foo3Obj];
AvGen.theBody.bodyColor = '#DB6EDB';
AvGen.theBody.currBodyNr = 1;
AvGen.theBody.currBodyObj = AvGen.theBody.bodies[1];
// and so forth..

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 benefit of writing in this manner?

Additional Module Insights available on redirectmodulenotes.com. Here is an example of how a module can be written: define(["require", "./another/name"], function(require) { var mod = require("./another/name"); }); Alternatively: define(function(req ...

Refreshing MongoDB data by utilizing values from an object

I am facing a challenge with my MongoDB collection structure: [ { "stock": "GOOGLE", "price": 0 }, { "stock": "FACEBOOK", "price": 0 } ] On the other hand, I have a Stock_P ...

Converting a for loop into a fixed-size array?

I am currently developing a backbone application and have been given some sample code by the provider. The code includes a for loop that generates player names as 'player_1', 'player_2', and so on. However, I would like to manually ente ...

Developing a feature that triggers an event upon closing a window with Javascript

I am developing a popup that enables me to choose values from it. Once I have selected the values, I need to close the window and transfer the data to my main form. Below is the code in my main form: onClick="cust=window.open('popup.php?count=<?= ...

How does the method of including JavaScript libraries in HTML differ from adding them as npm dependencies?

Upon browsing through npm highly regarded packages, I noticed that popular projects such as Grunt, lodash, and underscore are readily available. I have always utilized these in the traditional manner: <script src="js/lib/lodash.min.js"></script& ...

Refreshing chord chart information from a JSON source in d3.js

I have two functions that are responsible for creating and drawing a D3 chord diagram representing the netflow between different IP addresses in our network. Function 1 (for creating the chord diagram) function createChords(jsonURL, containerID, tooltipI ...

Sending an Ajax call to a PHP script without including any data in the POST

Having recently started delving into javascript, I've encountered an issue with performing an ajax POST to php. I'm attempting to send javascript variables over to php through an ajax POST, but it seems to be malfunctioning. The ajax post goes ...

I am trying to implement a "back to top" button/function for a horizontally scrolling page, but it doesn't seem to be showing up as expected. Is there a way to make this work?

I came across a similar question, but unfortunately it didn't provide the solution I was looking for. My goal is to include a "back to top" button on a side-scrolling page. Despite the inverted axis, I believe it should behave similarly to a regular b ...

The pagination feature in DataTable does not retain the edited page after making changes

I have been encountering an issue while using DataTable serverside processing. My datatable includes an edit column, and when the edit link is clicked, a jQuery dialog box appears. After submitting the dialog box, an ajax.reload call is made. However, the ...

What is the best way to compare JavaScript arrays with the same items but in a different order?

Within my product groups, each group is identified by a set of product_type_ids. I am looking for a way to match different groups based on their product_type_ids. The order of the ids may vary within the group, but as long as the sets of ids match, I cons ...

Disconnecting a Metamask Wallet in an Angular application: A Step-by-

I need assistance with disconnecting a Metamask wallet using web3 in Angular. //this is my wallet connection code async connectWallet() { const accounts = await this.ethereum.request({ method: 'eth_requestAccounts', }); this.selectedAddress ...

Setting the state variable value asynchronously using AngularJS UI-If

Is it possible to limit access to the sidebar until the user has completed the login process? The sidebar is located outside the main ui-view section I am assuming that authenticated is a state variable <div ng-controller="MyController" ui-prevent-to ...

What is the most efficient way to extract the largest number from a textarea?

Here's the scenario: I have a textarea with text enclosed in square brackets like so: <textarea> this is a test [1] also this [2] is a test and again [3] this is a test </textarea> The task at hand is to extract the largest number found ...

Regular expression: retrieve the text following every colon

Consider the following string: "abc:12:toto:tata:titi" To extract each string after ":" using split(), you will get "toto", "tata", and "titi" in this scenario. ...

Updating the load context variable in Django template after making changes via an AJAX call: a step-by-step guide

Here is the code snippet for displaying table items in my customer_items.html page: <table id="tblData" style="width: 100% !important;" class="display table table-bordered table-striped table-condensed"> <thead> <tr> ...

Having trouble with changing the state within an AngularJS (Ionic Framework) controller?

My goal is to switch views within the Search controller after receiving search results from the server through $http. However, my current approach doesn't seem to be working as intended. I also need to pass the response to the new view for displaying ...

Storing form datepicker data into MongoDB using Node.js

Having an issue with the date formatting between Angular Material 6's Datepicker and Node.js. When displaying the date in the browser, it shows as 06/20/1992, but in the console output, it appears as Sat Jun 20 1992 00:00:00 GMT+0800 (Philippine Stand ...

Is it possible for two separate tasks operating concurrently to access and modify the same array simultaneously?

Imagine you have an array being altered by one asynchronous process and then another asynchronous process reading from the same array. The modifications and reads happen synchronously. So, the big question here is: can the read process somehow access the a ...

When the background image is concealed, the table will have no border

Is there a way to retain the borders inside the table even when the background images are hidden? I am using JS and jQuery to add the picture when the site is loaded. Below is a snippet of my HTML and CSS: <!DOCTYPE html> <html> <head> ...

Is there an issue with the proper execution of keypresses/updates in the code

I'm currently stuck while trying to develop a game in Javascript. My challenge lies in detecting keypresses and constantly checking if they are being held down to move the character. Below is the code I have been using: var THREE; var keys; var updat ...