Storing data in a two-dimensional array using JavaScript

I have noticed that most examples of nested arrays are structured like this:

var arr = [1, 2, [3, 4], 5];

alert (arr[2][1]);

However, I am curious about a different structure. Here's what I have in mind:

var mmo = [];

mmo["name"] = "steve";
mmo["name"]["x"] = "20";
mmo["name"]["y"] = "40";

alert(mmo["name"]["y"]); // I expect it to alert 40 but it shows as undefined

Answer №1

It is not possible to have both a value and an array within the same item.

To address this, consider using an object instead of an array. This way, you can utilize named properties instead of numeric indices.

You can nest objects within objects by setting them as properties:

var mmo = {};

mmo["name"] = {};
mmo["name"]["x"] = "20";
mmo["name"]["y"] = "40";

If you prefer to use an array within an object, you would assign values using numeric indices:

var mmo = {};

mmo["name"] = [];
mmo["name"][0] = "20";
mmo["name"][1] = "40";

In case you need to use an array within another array, all elements will be indexed numerically:

var mmo = [];

mmo[0] = [];
mmo[0][0] = "20";
mmo[0][1] = "40";

While it's technically possible to use an array and include properties within it, this approach can lead to confusion due to mixed data types.

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

Transferring a boolean model value to a JavaScript function triggers a reference to the onchange function

An onchange event is triggered in an input tag of type checkbox, calling a JavaScript function and passing three parameters from the model: <input type="checkbox" ... onchange="changeRow('@Model.Id', '@Model.Type', @Model.AwaitingAp ...

Adhesive Navigation Bar

Check out this link: JSFIDDLE $('.main-menu').addClass('fixed'); Why does the fixed element flicker when the fixed class is applied? ...

Is there a way to access a JSON node dynamically without relying on the eval function?

Path variables can be unpredictable, ranging from just a to a/b, and even a/b/c. My goal is to dynamically reach a node based on the path provided. The code snippet below achieves this, but I am open to exploring alternative methods that do not involve usi ...

Customizing Axios actions in Vue JS using a variable

I have a form in my Vue component that sends a reservation object to my API for storage. I am exploring the possibility of setting the axios action dynamically based on a variable's value, without duplicating the entire axios function (as both the pos ...

Utilizing Arrays in Matplotlib: A guide to plotting data stored within an array

In my code, I have 200 co-ordinates stored in two arrays called plotx_array and ploty_array. Below is a snippet of the code used to plot these arrays: i = 0 while(i<200): print plotx_array[i], ploty_array[i] plt.plot(plotx_array[i], ploty_array[i ...

Simultaneous fading and displaying of the navbar

Currently, I'm in the process of constructing a navigation bar using Bootstrap v4 and have encountered an issue with the collapsing animation in responsive view. Upon inspection of the specific navigation bar, I noticed that the classes (.in and .s ...

Error encountered: Jquery - function is not defined

Currently, I am developing a widget that is integrated into a client's website and it loads a jQuery file. However, we need to check if jQuery is already loaded on the client's page to prevent any conflicts, in which case we would not load our ow ...

ASP.NET MVC Dropdown Group List with AJAX Request

I'm currently facing an issue with the DropDownGroupList extension for ASP.NET MVC 5. My goal is to dynamically populate the control using JavaScript and data from an AJAX request. I've managed to achieve this for the DropDownList control, but I& ...

Display content in a specific div when the page is first loaded

I am currently working with the following code snippet: HTML: <div class="content-class"></div> JQuery Ajax: $(document).ready(function() { $(document).on("click", ".content-class", function(event) { event.preventDefault(); ...

Insert a datum into an existing element

I need to modify a link by removing the title attribute and instead placing the title text in a data attribute called data-title. I want to achieve this using jquery. Can someone please provide guidance on how to do this? The goal is to remove the title e ...

Allow for the inclusion of periods and spaces when coding in JavaScript

My JavaScript code checks if the username meets certain criteria. // Check the username re = /^\w+$/; if(!re.test(form.username.value)) { alert("Alert"); form.username.focus(); return false; } Currently, the script only accepts lette ...

Pass a column of a 2D array into a 1D array in the JAVA programming language

Is there a way to convert a column of a 2D array into a 1D array? In order to provide clarity, I created this example but am uncertain about how to execute the print function. public static void main(String[] args) { double[][] matrix = {{ 0,1,2}, ...

I am interested in executing a series of consecutive queries to MySQL through Node.js, however, only the final query seems to be executed

connection.query(listprofiles,function(error,profilesReturned){ console.log(profilesReturned.length) for (var i=0;i<profilesReturned.length;i++){ console.log(profilesReturned[i].column) var query2='SELECT IF(COUNT(*) & ...

An error in Webpack prevents it from resolving the data:text import

I built an app that relies on a third-party library with the following syntax: const module = await import(`data:text/javascript;charset=utf-8,${content}`); While using Webpack to build the app, I encountered this error: ERROR in ./node_modules/@web/test- ...

What is the best way to combine two bytes in Java?

I have a variable named writePos which holds an integer value between 0 and 1023. My goal is to store this integer in the last two bytes of a byte array called bucket. To achieve this, I need to express it as a combination of the array's final two byt ...

Collection of numerical values in C#

Looking for help with reading a text file that contains a list of numbers? Here are the specific requirements: Determine the total number of numbers in the file Calculate the sum / matrix product of the numbers Find the minimum, maximum, and average valu ...

The functionality of the second range slider appears to be malfunctioning within the HTML

I am experiencing an issue with the range value sliders in my form. Only the first slider is functioning correctly. Below is a snippet of my code: $('#listenSlider').change(function() { $('.output b').text( this.value ); ...

Moving PHP array values between two different sections on a webpage using the transfer (add/remove) method

In my div, there is an input textbox that can be manually edited. I am trying to dynamically add or remove PHP values from another div that contains a set of array values obtained from a query. Each value in the array has an [Add] or [Remove] button depend ...

Storing Dark Mode Preference in Local Storage using JavaScript

I recently implemented dark mode on my website and it's working flawlessly. However, every time I refresh the page, it reverts back to the default Day Mode view. Is there a way to save these preferences? In the HTML section: <body> &l ...

Looking to spice up your website by incorporating a menu and setting up navigation throughout your pages using AngularJS?

Here is a snippet of HTML code that allows users to enter a movie title and displays search results. I am looking to add a menu to this page, with links redirecting to different pages such as 'About Us', 'Featured Films', and 'Sea ...