Learn the process of extracting the value of a specific key from an array using Java Script

I have initialized a static array as shown below:

country["0"]=[USA];

state[country[0][0]]=[["NewYork","NY"],["Ohio,"Oh"]]

for (var i = 0; i < state[country[0][0]].length; i++) {
    var key = state[country[0][0]] [i][0];
    var value = state[country[0][0]] [i][1];
}

In the above loop, I am able to access the keys of states like NewYork and Ohio. Can someone guide me on how to retrieve the values "NY" and "OH"?

Answer №1

let result = state[country[0][0]] [i][1];

Answer №2

Your code contains a few mistakes that need to be addressed. Let's assume the variable country holds a list of countries and the variable state stores information about states within each country...


country = ["USA"];
state = {"USA": [["NewYork", "NY"], ["Ohio", "OH"]] };

for (var i = 0; i < state[country[0]].length; i++) {
    var key = state[country[0]][i][0];
    var value = state[country[0]][i][1];
}

Answer №3

Oops, looks like there's a typo here

state[country[0][0]] = [["NewYork","NY"],["Ohio", "Oh"]]

To retrieve ["NY", "Oh"], you can use the following code snippet:

for (var i = 0; i < state[country[0][0]].length; i++) {
    var key = state[country[0][0]][i][0];
    var value = state[country[0][0]][i][1];
}

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

"Utilizing AJAX to dynamically extract data from PHP and manipulate it in a multi-dimensional

Just starting out with JSON/AJAX and I'm in need of some help... I have a PHP page that seems to be returning [{"id":"1"},{"id":2}] to my javascript. How can I convert this data into something more user-friendly, like a dropdown menu in HTML? Here i ...

Why does the styling of the inner Span adhere to the style of the outer Span?

How can I adjust the opacity of the color "blue" to 1 in the code snippet below? <!DOCTYPE html> <html> <body> <p>My mom's eyes are <span style="color:blue;font-weight:bold;opacity:0"> <span style="color:blue;fo ...

Tips on attaching a suffix icon to a material-ui-pickers input box

Here is a snippet of my code: <Box p={6}> <Grid container spacing={2}> <Grid item xs={6}> <TimePicker autoOk label={t('checkIn')} value={time1} onChange={handlecheckIn} clearable /> </Grid> < ...

Why does React component still use old state when re-rendering?

I recently encountered an issue with my code. I am using an array of objects in my state, and when I delete an item from the array, the component does not render correctly without the deleted object. Additionally, when I try to open another object (trigger ...

Is it possible to choose tags from a different webpage?

Imagine you have a page named a.html which contains all the jQuery code, and another page called b.html that only includes HTML tags. Is it feasible to achieve something like this: alert( $('a').fromhref('b.html').html() ); In essence ...

What steps can be taken to fix the "connection Timeout" issue?

const axios = require('axios'); axios.get('https://encrypted.google.com/') .then((res) => { console.log("Status Code: ", res.status); console.log("Headers: ", res.headers); console.log("Data: ", res.data); }) .catc ...

Tips for changing the content of a td element to an input field and removing the displayed value

I am facing an issue with a dynamic table that displays names and input fields. When a name is displayed in a table row, the user has the option to delete that name. I am able to remove the value from a specific table row, but I am struggling to replace th ...

Filtering an array by values that fall within the range of two other arrays can be achieved using JavaScript, especially

Within my possession are 2 arrays: var array1 = [{"name":"abc", "url":"http:://example1.com"}, {"name":"cde", "url":"http:://example2.com"}, {"name":"fgh", ...

Using jQuery to format a data value with content

Hovering over my price slider reveals a tooltip displaying the slide price. As the slider is moved, the values in the tooltip change accordingly. I recently added the £ sign to the tooltip values, but I need help correcting its position as it currently ...

Is it possible to pass arguments to setTimeout function?

At the current moment, my code looks like this: function showGrowl(lastNumber) { var num = lastNumber; //keep generating a random number untill it is not the same as the lastNumber used while((num = Math.ceil(Math.random() * 3)) == lastNumber); ...

`Utilizing Symbolic Links to Share Code Across Multiple React Applications`

Presently, I have developed two distinct frontend applications. One is a lightweight mobile client, and the other is a heavy administration panel. Both of these were built using Create React App (CRA), utilizing TypeScript throughout. The current director ...

Issue with an external library in Angular 2

After generating my Angular 2 library using the yeoman generator and adding it to my main Angular project, I encountered errors when running the app in production mode. The specific errors include: WARNING in ./src/$$_gendir/app/services/main/main.compone ...

Issue encountered with AJAX request using JavaScript and Express

I'm brand new to this and have been searching online for a solution, but I can't seem to figure it out. It's possible that I'm making a basic mistake, so any assistance would be greatly appreciated. I'm trying to create a simple f ...

GATSBY: Error: Unable to find the specified property 'includes' within an undefined value

I'm struggling to figure out how to properly filter images in my portfolio website as discussed in this post… Every time I attempt it, I encounter the following error: "TypeError: Cannot read property 'includes' of undefined" D ...

Implementing class using Javascript

I have a JavaScript function that switches grid images when clicked. It also delays the href to the second click, allowing the switched image to be displayed. What I want to achieve is to add a class on the first click, triggering another JavaScript code ...

Utilize the power of both $push and save functions in MongoDB for efficient

While developing my pet application, I encountered a problem. I am using nodejs and the mongojs library to interact with MongoDB. The code I wrote goes like this: db.users.findOne({_id: ObjectId(id)}, function (err, doc) { if (err) { res.sta ...

Client-side resizing an image before sending it to PHP for uploading

Greetings! Currently, I am utilizing a JavaScript library from this source to resize images on the client-side. The image resizing process works successfully with the following code: document.getElementById('foto_select').onchange = function( ...

The validation process for the mongoose model failed due to incomplete input fields

Having trouble saving the submission model object with a one-to-one mapping with the Form and User models. submission.model.js const mongoose = require('mongoose') const Schema = mongoose.Schema const submissionSchema = new Schema({ form: { ...

Encountering Java ArrayOutOfBoundException repeatedly when attempting to identify the most frequently occurring word within a file

Currently, I am in the process of developing a program that reads a file and displays the most frequently occurring words along with their respective frequencies. Here is a snippet of my code: package WordLookUp; import java.util.*; import java.io.*; imp ...

Guide to flattening a nested array within a parent array using lodash

Within my array named sports, there is another array called leagues, but I need to flatten these arrays using _.flatten due to issues with Angular filters. If you look at the data, inside the first array which contains a "name":"Live Betting", there is an ...