Exploring the use of nested arrays in JavaScript: accessing elements in different modules

Could you provide an example of a nested array that can be accessed across ES6 module boundaries with setter and getter methods from a dependent module?

While setter methods work fine, invoking getter methods across module boundaries always results in:

TypeError: nested_array[at_whatever_depth] is undefined

I am trying to simplify complex examples by modularizing the code. Here's what I've attempted so far:

The original code populated and used the array within the same scope. Now, I'm trying to modularize it for better organization.

This code prepares imported music font ('glyphs') for display using a state module approach.

var music_glyphs_store = (function () {

  var pub = {};

  pub.state = [],

  pub.setGlyphByName = function (glyph_name, horiz_adv_x, path) {
    pub.state.push(glyph_name);
    pub.state[glyph_name] = [];
    pub.state[glyph_name]["glyph_name"] = glyph_name;
    pub.state[glyph_name]["horiz-adv-x"] = horiz_adv_x;
    pub.state[glyph_name]["d"] = path;
  },

  pub.getGlyphByName = function(glyph_name) {
    return pub.state[glyph_name];
  }

  return pub; // expose externally
})();

export { music_glyphs_store };

The issue arises when calling music_glyphs_store.getGlyphByName() from the dependent module. The glyphs are stored in the array but cannot be accessed.

Here's how typical font elements look like in the original svg file:

<glyph glyph-name="scripts.sforzato" unicode="&#xe100;" horiz-adv-x="219"
d="M-206.864 126.238c-8.498 -2.679 -12.964 -10.131 -12.964 -17.821c0 -6.455 3.146 -13.0777... />

Imports are set up as follows:

import { music_glyphs_store } from "./music_glyphs_store.js";
import * as d3 from "d3";

After loading and parsing raw xml strings, data is added to the array using set methods:

d3.selectAll(note_glyphs.getElementsByTagName("glyph")).each(function(d, i) {

    var glyph_name = this.getAttribute("glyph-name");
    var horiz_adv_x = this.getAttribute("horiz-adv-x");
    var path = this.getAttribute("d");

    music_glyphs_store.setGlyphByName(glyph_name, horiz_adv_x, path);
});

The goal is to retrieve these values later using the get methods. For example:

console.log("index.js: Recovering " + music_glyphs_store.getGlyphByName("brace446"));
console.log("index.js: Recovering " + music_glyphs_store.getGlyphByName("accidentals.natural.arrowdown"));
console.log("index.js: Recovering " + music_glyphs_store.getGlyphByName("noteheads.s2slash"));

I have tried different approaches to conform to ES6 module standards without success. The problem may lie in the visibility/scope of dynamically allocated memory in Webpack's context. Is using nested arrays in a diverse Webpack environment possible?

Answer №1

It seems there may be confusion between arrays and objects. Arrays consist of sequential lists where each cell is identified by an integer index. In your code, glyph_name and unicode are being pushed onto the state array, creating the next element in the sequence, but then you're trying to access the array using glyph_name and unicode as indices. Consider using objects instead of arrays. Modify these lines:

pub.state = [];
pub.state[glyph_name] = [];
pub.state[unicode] = [];

to

pub.state = {};
pub.state[glyph_name] = {};
pub.state[unicode] = {};

Answer №2

Even though it may not be the correct approach, I am keeping this answer here to demonstrate what can be considered "array abuse," as mentioned by @Bergi in the comments.


The puzzling aspect in this situation was that the initial code worked without any issues. It only encountered problems when integrated into Webpack. This implies that structurally everything might be fine, but there were likely underlying issues with the previous implementation.

Through a bit of experimentation, I discovered that I could fetch array values across module boundaries by wrapping glyph_name in parentheses. For instance:

pub.getGlyphByName = function(glyph_name) {
  return pub.state[(glyph_name)];
},

However, 1) I do not fully comprehend what is going on, and 2) it seems precarious.

The original call from the external dependent module would remain unchanged as indicated in the initial question.

--> While I managed to resolve the immediate issue using this method, it involved exploiting arrays in an unconventional way.

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

Setting references to child components with VueRouter in Vue

I've written the following code snippet in my main.js file for my Vue web application: const routes = { name: "Main", path: "/main", redirect: "/main/home", component: MainComponent, children: [ { path: &quo ...

Using JavaScript to post data to a PHP script, then triggering the execution of another

My website has two distinct pages with different purposes. On one page, there is a button that, when clicked, sends data to finalizecontract.php. The other page, contract.php, creates a TCPDF form populated with the database information and saves the resu ...

Is there a way to access my JavaScript library from Angular?

How do I incorporate my JavaScript library into Angular? I have a JavaScript file named eletronic-prescription.js function EletronicPrescriptionReport(data) { var wrapper; var medicineIndex; var itemsPerPage = 3; var prescriptionDate; ...

VueJS modal displaying data acts strangely

While using vueJS and Laravel, I encountered an issue with my modal losing its shape when I tried to display data in it. Even duplicate forms failed to show the data correctly. This occurred when I clicked on a button to open the modal and show the data. ...

After clearing the option, the onChange function stops functioning

I'm facing an issue with the following code: success: function (data) { $('#' + idDivRefresh).endLoading(); if (data.message != '@Geral.Sucesso') { $('#' + idDropDown + ...

Load Express JS router middleware conditionally based on certain conditions

In my Express JS code, I have implemented a middleware that defines specific end-points on a router for user login and logout. However, I am now integrating a new authentication method where the auth token is received from a different service. In this case ...

How can I retrieve text from a file using terminal command?

Can anyone help me with writing a terminal command to extract text from an HTML file using specific tags like <li>, <strong>, <b>, <title>, <td>, etc. along with assigning variables and utilizing JavaScript functions via msgst ...

Press the delete button located on the child component to trigger an action in the

I'm in the process of developing a simple to-do application from scratch in order to familiarize myself with ReactJS. One challenge I'm facing is implementing the delete functionality for todos, as I want to keep the button within the Todo compon ...

Saving a complicated schema in Node using Mongoose fails to save or update when encountering an error

Greetings, I am facing challenges while trying to save a complex schema in MongoDB. const itemsSchema =new Schema({ cat: {type: String, required: true}, catItems: [{ items:{type: String}, isActive: {type: Boolean, default: true} }] }) ...

Execute JavaScript function with a delay once the webpage has finished loading

I am currently working on a basic function that runs when the page is loaded. However, even though the page has finished loading, there are times when it takes about half a second for the content to actually appear. While this typically wouldn't be an ...

How can I make a jQuery image hover and follow the cursor when hovering over any "a" link?

Hey there! I came across a code snippet on this particular post. What I'm trying to achieve is to have a PNG image display next to the cursor when it hovers over a hyperlink or any "a" link. Here's the original code: var $img = $('img&apos ...

Discover an Effective Approach for Transmitting Form-Data as a JSON Object

Hey there! I'm encountering a bit of an issue with sending some data as a JSON object. The problem arises when trying to send images using FormData. It seems like I need to convert my form data into a single JSON object. Can anyone assist me with this ...

I am having trouble retrieving the item from MongoDB using the React Native and Node.js combination

Within my index file, I have an API that retrieves a product from the database using a unique productId. After copying and pasting a specific productId from Mongo Atlas into Postman to test the API, it successfully retrieved the product as expected. Below ...

When transitioning to an object, Vue.js fails to refresh

My component contains an object called elements: elements: { id: { text: '', color: '', ... } To modify it, I use: <a-textarea autoFocus placeholder="text to include" :style="{ width: &ap ...

Is the Utilization of Inline JavaScript in HTML Attributes by Angular considered a "good practice"?

While going through the Angular tutorials, I found a lot to like. However, I couldn't help but wonder if "ng-click" is not essentially just an inline onClick function. My understanding was that the JavaScript community frowned upon using inline JavaSc ...

Adjust the sequence of the series in dimple's multi-series chart using interactive features

My latest project involves a unique dimple interactive chart featuring two series: a pie series and a line series based on the same dataset. You can view the chart at dimplejs.org/advanced_examples_viewer.html?id=advanced_interactive_legends Check out the ...

Issue with inserting dictionary object containing nested array into MongoDB using pymongo

I am attempting to insert dictionary objects into MongoDB using this Python script: result = centros.insert(clinica) where 'clinica' is the dictionary object being inserted. The first set of data provided below is successful: { 'Genera ...

Please provide a validation error message when attempting to select a dropdown list while the checkbox is unchecked

There are 7 drop down menus in a table row. When trying to select a value from the drop downs with the checkbox unchecked, a validation message should be displayed saying "Please enable the checkbox". If the checkbox is checked, all the drop down menus sh ...

Refresh the vue-chart component in a nuxt.js application

I'm currently working on a nuxt project and I need to incorporate some charts into it. I'm using vue-chartjs as a plugin for this purpose. However, the issue I'm facing is that the chart data is fetched after the chart has already been drawn ...

Tips for retrieving and organizing multiple values from a form using php

I am struggling to understand how to properly create this type of form. Unsure if my current approach is correct. The form I have created generates a delivery based on a list of products in the SQL table, each with a unique product ID and quantity. https ...