Accessing a specific value from a key in a JavaScript object array

My data structure consists of an associative array indexed by dates, with each element containing another array.

[03/16/2015: Array[3], 03/17/2015: Array[3], 03/18/2015: Array[3], 03/19/2015: Array[3]]

The array was created using the following code:

 array[cellDate][i]=cellText;

I am trying to retrieve a specific value from the array, for instance, cell 03/16/2015 array[2]. However, when I use this line of code:

 var text=array['03/16/2015'][2]; 

An error occurs.

EDIT:

In this array, I store titles of blocks on the schedule, assigning 'empty' if the cell is empty.

My goal is to maintain the order of blocks for different weeks and dynamically load blocks based on the date withdrawn from the array when the user navigates through weeks.

The function used to create the array is as follows:

function saveWeekToArray(array){
    var cellDate;
    var cellText;
    var tmpText;
    var i;
    workoutsTD.each(function(){
        cellDate=$(this).attr("data-day");
        array[cellDate]=['','',''];
        i=0;
        $(this).children('.workout-cell').each(function(){ 
            if (!$(this).hasClass('workout-cell-empty')){
                cellText=$(this).find('span').text();
                array[cellDate][i]=cellText;
            } else {
                array[cellDate][i]='empty';
            }
            i++;
        });

    });
}

The function that loads data from the array (the one causing the error) is as follows:

function loadBlocksFromArray(array){
    var cellDate;
    var cellText;
    var tmpText;
    var i;
    workoutsTD.each(function(){
        cellDate=$(this).attr("data-day");
        i=0;
        $(this).children('.workout-cell').each(function(){ 
            if ((array[cellDate][i])!='empty'){
                cellText=array[cellDate][i];
                $(this).append(createBlock(cellText));
                $(this).removeClass('workout-cell-empty');
            }
            i++;
        });

    });
}

If you click submit button, the console log will display the structure of the array.

The error I encounter while changing weeks is:

enter code hereUncaught TypeError: Cannot read property '0' of undefined

Answer №1

Unlike other programming languages, Javascript does not support the concept of an associative array. Instead, you can use arrays (indexed by numbers) or Objects (indexed by strings).

To achieve a similar functionality, you can create an object that contains all your arrays like this:

var information = {
  '5/12/2021' : ['data1', 'data2', 'data3'],
  '5/15/2021' : ['data4', 'data5', 'data6']
};

Then, you can easily access elements in the format you desire:

var element = information['5/12/2021'][0];

Answer №2

https://jsfiddle.net/abc123/

This is the exact outcome I was aiming for. Big thanks to Harvtronix for the helpful tip!

var workoutData = { routine : {} }

var x;
var y;
var exercisesArray = [];

for(x=1; x<=7; x++){
    var newExercise = x + "/12/2015";
        for (y=0; y<=2; y++){    
            var exerciseValue = "exerciseTitle" + y;
            exercisesArray[y] = exerciseValue;
        }
    workoutData.routine[newExercise] = exercisesArray;

}

console.log(workoutData);

for(x=1; x<=7; x++){
  var newExercise = x + "/12/2015"; 
   var tmpArray = workoutData.routine[newExercise];
     console.log(tmpArray);

}

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

Modifying the class of an HTML element using JavaScript

Is it possible to dynamically change the class of an HTML element based on a user's selection with a radio button? I am facing an issue where I receive the following error message: "Error: missing ) after argument list Source File: website Line: 1, C ...

Expanding Perspective in React Native

Having trouble with implementing a camera feature that isn't scaling correctly. The issue seems to be related to the styling of the container View, as when the camera is rendered independently it works fine. The goal is for the camera to activate when ...

Exploring the concept of Javascript Objects and the undefined value

I've encountered an issue with a Wordpress plugin that is no longer supported. After some investigation, I have identified the problem area in the code: i[C][0]; The above line seems to be causing an 'undefined' return within the function ...

The TypeAhead feature fails to display any search results for the entered query

Feeling really desperate right now! I'm facing a frustrating issue with Bootstrap Typeahead. Here is the HTML Markup: <div class="form-group"> <label for="">Recipients</label> <input id="recipients" name="recipients" ...

A Vue.js component modifies one store state variable but leaves another unchanged

Currently developing a Vue 3 application that utilizes Vuex and the Composition API. Encountered an issue while working on it. A component is supposed to display elements based on the state of two store variables. One is an array, and the other is a bool ...

The positioning of images on the fabricjs canvas seems to be unreliable and inconsistent

When trying to place a series of 4 images at specified coordinates in fabricjs, I am facing inconsistencies with their placement upon page load. Refreshing the page usually resolves the issue, but I want to prevent this from happening altogether. If anyon ...

Retrieve the values of input fields once the button is clicked in JavaScript

Welcome to my question section! I have an interesting task at hand and would appreciate your input. After clicking the #grabValues button, I want to save the input values in an array for calculating total hours. For this project, I plan to write the neces ...

What is the best method for iterating through VBA rows without stopping at the final row?

Recently started learning VBA and I am attempting to calculate the total hours from cells based on inputting start and end months through input boxes. My goal is to calculate the sum of cells by looping through each row. Currently, my program works if I en ...

Sort your Laravel pagination table effortlessly with just one click

Here is my current setup: <table class="table table-striped"> <tr> <th> Item Image </th> <th> Item Number </th> <th> Item Name </th> <th> Description </th> ...

Why does Jquery refuse to accept hyphens in the JSP page?

I received a field from SERVICE that contains a hyphen. For example, first-name (as a JSON object). However, when I attempt to retrieve the value of this field in my JSP file, I encounter a script error. Can you please advise me on how to properly access ...

What is the best way to navigate to a different page, such as Google, using Node.js?

I need to retrieve a number to store in a short variable, and then search the database for a corresponding shortUrl associated with that number. If a match is found, I want the response to be the full URL, such as www.google.com. For example, if a user ty ...

Changing div height based on the height of another dynamic div

Looking to create a box that matches the height of the entire page, live height minus another dynamic div called #wrapping. I have code that offsets it instead of removing the height of the div... function adjustBoxHeight() { var viewPortHeight = $(wind ...

One package in Node.js, a pair of dependencies, and a single export utilizing ES6 syntax

Currently, the library contains multiple frameworks in one npm module (which is admittedly not the best practice). However, as we work on splitting the library into separate JS framework specific repositories like React, JQuery, Angular, etc., I'm fac ...

Mastering the art of utilizing AJAX for autocomplete functionality

While utilizing the autocomplete feature from jqueryui (http://jqueryui.com/autocomplete/#remote) and fetching data from "source: "search.php"" The following script ... $( "#name" ).autocomplete({ source: "search.php", minLength: 2, select: function( ...

Element enclosed within a territory of mongoose Schema

In the midst of developing an API that provides detailed information about laptops, I am utilizing Node.js and MongoDB with Mongoose. The schema I am working with is as follows: const productSchema = mongoose.Schema( { name: { type: String, ...

Identify and mark JavaScript variables that are not being utilized

Currently utilizing JSHint and JSCS for JavaScript code validation, but neither of them can identify the presence of unused variables like in this example: describe('XX', function () { var XXunused; beforeEach(inject(function ($injector) { ...

Ways to apply CSS to a changing div ID

I am looking to apply CSS to a dynamically generated div ID. var status = var status = item.down().next().innerHtml(); if(status == "test") { var c = 'item_'+i ; c.style.backgroundColor = 'rgb(255, 125, 115)'; //'ite ...

Can we spice up the button with some animation while waiting for the ajax call to complete? Just a little something to

My HTML page features a button that triggers an AJAX call when clicked. During the call, the text on the button is replaced with animated dots to indicate progress. However, there is an issue where sometimes the call takes several seconds, while other time ...

Ajax received a response from http 409 and is now parsing it

Hey there! I've been working on parsing out the message object using Ajax, and I'm having a bit of trouble getting a reference to messages.msg. It's strange because it displays perfectly fine in Postman, but for some reason, I can't see ...

Utilize Typescript or JavaScript to dynamically access the names and values of class members

I'm relatively new to these programming languages and I know it may not be too difficult, but I am struggling to figure out how to dynamically access class instance variables. My goal is to display an instance's variables in a table using Angula ...