The two-dimensional array in JavaScript has not been defined

I've been trying to troubleshoot the error in my code with no success. I have a simple example of what I believe to be a two-dimensional array, but I keep getting an undefined error.

var city = 'London',
    country = 'England';

var locate = [];
locate['London']['England'] = ['Jhon','Mike'];

for (i = 0; i < locate[city][country].length; i++) {  
  console.log(locate[city][country][i]);
}

Check out the jsbin http://jsbin.com/pixeluhojawa/1/

I'm struggling to figure out what I'm doing wrong in this example. Any help would be greatly appreciated.

Answer №1

To assign a value to locate['London']['England'], first ensure that locate['London'] is an object:

var locate = {};
locate['London'] = {};
locate['London']['England'] = ['Jhon', 'Mike'];

Instead of using array literals ([]), use object literals ({}) since arrays do not support string keys like this.

Another way to declare it is:

var locate = {
    London: {
        England: ["Jhon", "Mike"]
    }
}

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

In Vue, the CropperJs image initially appears small, but it returns to its original size after editing

I encountered a peculiar issue while working on a website for image cropping using Vue.js and CropperJs. On the homepage, users can select an image to crop and proceed to the next page where a component named ImageCropper.vue is displayed. Strangely, the c ...

AJAX, JavaScript, and hyphens

Can anyone help me understand why the ajax statement in my code does not accept the '-' symbol? I've had issues with this before and ended up modifying a lot of things on the backend of my site to use '_' instead, which worked. Is ...

Utilizing JavaScript for selecting a radio button on click event

I have implemented a feature with four radio buttons to select a country. Upon clicking on any of the radio buttons, I utilize Ajax to retrieve the states corresponding to that specific country. To indicate to the end user that data processing is ongoing, ...

Discover and transform any strings that begin with http & https into clickable links

Can I use jQuery to search a paragraph for all strings that begin with http & https and turn them into clickable links? I have my Twitter feed displayed on my website, but any lines starting with http & https are shown as regular text. Is it feasible to t ...

Different ways to rearrange the placement of Export buttons in a personalized div or outside the table using Datatable

I would like to display the export buttons outside of the table. While searching on stackoverflow, I came across an example that uses the Select options method. You can find the example here. If anyone knows how to achieve this, please modify it and shar ...

What is the best way to utilize mapping and filtering distinct values in an array using TypeScript?

What is the best way to filter and map distinct elements from an array into another array? I've experimented with various methods but keep encountering a syntax error stating "Illegal return statement". My objective is to display only unique items f ...

Deactivate the AJAX button after the specified number of clicks

Imagine I have a model called Post, and it can be associated with up to n Comments (where the number is determined by the backend). Now, let's say I have a view that allows users to add a Comment through an AJAX request. What would be the most effecti ...

Solve problems with limitations on ng2-dnd drop zones

I successfully integrated drag and drop capabilities into my Angular 4 application using the ng2-dnd library. Within my application, I have containers that can be sorted, as well as individual items within each container that can also be sorted. My goal i ...

After toggling the switch to send the current state to the server, the React state remained unchanged

Could you clarify why the relay1 state is being sent as false? Why doesn't handleControlRelay1 change the state? Am I making a mistake by placing this inside a function? setRelay1((prevValue) => !prevValue); // ... const [relaysData, setRelaysD ...

The current situation is not effective; it is causing an error saying "Uncaught TypeError: Cannot read property 'substring' of undefined"

Encountering an error "Uncaught TypeError: Cannot read property 'substring' of undefined" while debugging in Chrome Inspector, with the following code: <script type="text/javascript"> $(function countComments() { var mcount = '/ ...

What could be causing the images to not display on my HTML page?

My program is designed to display an image based on the result of the random function. Here is my HTML: <div> <h2>Player 0:</h2> <div id="MainPlayer0"></div> </div> Next, in my TypeScript fi ...

What is the best way to implement promise function in a JavaScript functional method such as forEach or reduce?

I have implemented a promise function in the following way: // WORK let res = {approveList: [], rejectList: [], errorId: rv.errorId, errorDesc: rv.errorDesc}; for (let i = 0; i < rv.copyDetailList.length; i ++) { const item = rv.copyDetailList[i]; ...

The proper method for developing Vue components that are dependent on the parent build tools

In my experience, this issue might also arise in other frameworks with plugin/component ecosystems that rely on specific build tools (such as React components with JSX). While Vue serves as my use-case. Having developed numerous Vue components as single . ...

Retrieving text that has been HTML-escaped from a textarea using jQuery

Within my HTML file, I have a <textarea id="mytextarea"></textarea>. Suppose a user inputs the following text: <hello>, world! How can I retrieve res = "&lt;hello&gt;, world!"; based on the user's input? The current code s ...

Tips for using res.json as a callback function

When using a function with a callback parameter, I found that this method works perfectly fine: DB.last(user,(data) => res.json(data)); However, when attempting to refactor it for better readability as shown below: DB.last(user,res.json); The structu ...

What is the most efficient method for storing text in my web application?

Hey there, I'm looking for a way to easily store and access the wording used in my application so that I can use them again whenever needed. For example, loading messages, validation messages, or informational messages are some of the wordings I want ...

What method does C++ use to determine the size of an array?

Exploring the Process of Size Calculation Instead of simply looking for the size of an array, I am curious about how the computer actually determines the size. Objective My goal is to uncover the method C++ uses to calculate the size of a one-dimensiona ...

AngularJS - automatically submitting the initial item

Is there a simple way to automatically select the first item in my ng-repeat when the list is loaded for the user? Currently, I am using ng-click, but I am unsure of how to automatically trigger a click on the first item. Here is my ng-repeat: <div n ...

Provide JSON data from the index method to the index.html file located in the public directory

I'm currently working on building a single page application using Rails as the backend, since it's the only framework I am familiar with. All my project files are stored in the public folder, and I've also set up npm and jspm to incorporate ...

When I attempt to utilize the API, the JavaScript implementation of a <script src=...> element seems to interfere

Within one of my HTML files, I encountered the following line near the top: <script src="//maps.google.com/maps/api/js?key=apikey"></script> The API key is currently hardcoded in this file, but I would like to use a configuration option store ...