Storing an inner object within a map using Javascript

   // Here we have a script that aims to store 3D mesh objects in a map
    // The problem arises when attempting to access the stored object later

    this.meshMap = new Object();

    // Function to add a mesh to the map using a specified key and URL
    this.addMesh = function(key, url) {
        var map = this.meshMap; // Reassigning the map variable to be used locally

        // Using THREE.JSONLoader to load the mesh from the provided URL
        var loader = new THREE.JSONLoader();
        loader.load(url, function(geometry) {
            // Storing the loaded mesh as an object in the map using the key
           map[key] = new THREE.Mesh(geometry, material);
           
           // Adding the mesh object to the scene
           scene.add(map[key]); 
         });

         // Attempting to set the position of the mesh after it has been loaded
         // However, encountering an error due to the object being null at this point
         map[key].position = new THREE.Vector3(0, -10, 0); 
     }

What is the correct way to store the mesh in the map so that it can be accessed without errors?

Answer №1

Ensure that the map[key] object (referencing this.meshMap) is properly initialized before calling addMesh function. It's important to distinguish between the fact that map[key] should be an object, not necessarily that map itself needs to be an object. Without map[key] being an object, it won't be able to have properties like position.

To address this issue, consider the following approach:

this.meshMap = new Object();

this.addMesh = function(key,url)
    {
      var map = this.meshMap; // redefine map

      var loader = new THREE.JSONLoader();

      loader.load( url, function(geometry)
      {
            map[key] = new THREE.Mesh(geometry, material); // create new object
            map[key].position = new THREE.Vector3(0, -10, 0); // ERROR: Null
            scene.add(map[key]); // Success
      });


    }

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

Tips on using CSS to hide elements on a webpage with display:none

<div class="span9"> <span class="disabled">&lt;&lt; previous</span><span class="current numbers">1</span> <span class="numbers"><a href="/index/page:2">2</a></span> <span class="num ...

Is the jQuery ajax connection established, but the response is empty?

I am currently experimenting with creating a test that involves ajax response utilizing an external array as a configuration file. However, I am encountering an issue where I consistently receive a blank response. Can someone help identify the reason behin ...

PHP strtotime is adding an extra hour to my time

Within my database table, I have a datetime stored as '2014-08-05 15:12:00'. After using strtotime() to convert this date to milliseconds, on the client side I create a new Date object as follows: var date = new Date(date_in_milliseconds) Ho ...

Implementing Dual Submit Buttons in Node.js using Express Framework

Struggling with implementing a like and dislike function in my node js app. Currently, I can only do one at a time. Below is the HTML code snippet: <form method="post" name="ratings"> <input type="submit" name="vote" value="like"> < ...

Utilizing sourcemaps in ionic for seamless linking

I've encountered an issue with source maps or a similar feature. After inserting console.log(...) in my code, the message appears in the console but links to the compiled JavaScript file instead of the original TypeScript file. Have I overlooked som ...

Angular click event not triggering as expected

Is there a way to automatically trigger an Angular element click event upon page load? $scope.fetchMealInfo = function (incomingDate) { angular.element(".trackNext a").on("click", function () { //alert(offset.left); console.log("inside ...

Vue3/Vuex - Issue with state change not being reflected in component when utilizing object destructuring

While working with Vue 3 and Vuex, I encountered an issue where Vue did not react to a state change when using object destructuring assignment to mutate the state. However, I found that Vue does react when the state is mutated by a mutation that only reass ...

Ways to determine if an AngularJS modal is currently displayed

I am currently in the process of determining whether a modal is opened or closed. However, I keep encountering an error that says "cannot read property of open." To address this issue, I realize that I need to connect with $modal.open and retrieve the resu ...

Creating a "Mark as Read" function using localStorage

Looking for a solution to persist the state of "Mark as Read" or "Mark as Unread" even after refreshing the page? Want to use localStorage to save this data? Here's an example of code snippet for toggling between these states: function readunread() { ...

Babel is failing to transpile the Modal component from material-ui-next to ES5

Issue with Babel transpiling Modal component from material-ui-next Here is my .babelrc configuration: { "presets": ["es2015", "react", "stage-1", "stage-2", "stage-3"] } This is the webpack-config.js setup: var webpack = require('webpack'); ...

iOS users may find that when a web page loads, it is often already scrolled halfway down

Encountering a problem with a long-scroll website that I'm currently developing. Whenever I access the page on my iPhone, the initial scroll position is consistently halfway down or near the bottom of the page. I've attempted to troubleshoot by d ...

Error encountered due to a circular reference in the dependency library

Whenever I attempt to run my application, I encounter the following error: > npm start Starting the development server... ts-loader: Using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42363b32273121302b323602716c776c71"& ...

Using an ASP.NET control along with jQuery within a standalone .js file

I recently created a jQuery voting script that functions perfectly when the code is kept within the header of the page. However, I am interested in transferring it to a separate .js file and simply including this .js file at the top of the page. Strangely, ...

The sequence of initializing test hooks in inconsistent playwright tests

My testing framework setup looks something like this: test.describe("...", () => { let p: Page; test.beforeEach(async({browser}) => { p = await (await browser.newContext()).newPage(); } test(...); test(...); test.aft ...

Switch up row values in an array and transform them into an object using SheetJS

I am struggling to format an array where each "Working Day" is represented as an object with specific details like index and start/end date. I need help manipulating the JSON data to achieve the desired structure. The package I'm currently using is: ...

Identify when users reach the end of a webpage through scrolling using mousewheel actions and scroll events

I want to track when a user reaches the end of a page and tries to scroll further, even though there is no more content to see. One of my usability metrics includes identifying dead scrolls, so I need a reliable way to detect when users attempt to scroll ...

Issue with form array patching causing value not to be set on material multiple select

When attempting to populate a mat-select with multiple options using an array of ids from Firestore, I encountered an issue. The approach involved looping through the array, creating a new form control for each id, and then adding it to the formArray using ...

Experiencing difficulties with JavaScript/jQuery when encountering the 'use strict' error

I have been working on a small function to change the background of an HTML file, but I keep getting the 'Missing 'use strict' statement' error message from JSLint despite trying multiple solutions. Can anyone suggest how to resolve th ...

Angular - the utilization of expressions in view templates

Exploring Angular for the first time and attempting to create a Single Page Application (SPA). I have included the route module, which seems to be functioning properly. However, the templates are not interpreting Angular expressions as expected - for examp ...

Utilizing the js-yaml library to parse a YAML document

Currently, I'm utilizing js-yaml to analyze and extract the data from a yaml file in node js. The yaml file consists of key-value pairs, with some keys having values formatted like this: key : {{ val1 }} {{ val2 }} However, the parsing process enco ...