Elby
Elby

Reputation: 1674

Create mutidimentional Associative array in javascript

I need to create a multidimensional array in JavaScript

My code as follows but get console error "Uncaught TypeError: Cannot set property 'time' of undefined"

 var timeLogDetails = {};
  $('.time_input').each(function(i, obj) {
       timeLogDetails[i]['time'] = $( this ).val();
       timeLogDetails[i]['timeLog'] =  $( this ).attr('timelog');
  });

Upvotes: 1

Views: 57

Answers (2)

dfsq
dfsq

Reputation: 193301

You can use each like demonstrated by BenM, or $.fn.map. Both will produce array of objects:

var timeLogDetails = $('.time_input').map(function() {
    return {
        time: this.value,
        timeLog: $(this).attr('timelog')
    };
}).get();

Upvotes: 1

BenM
BenM

Reputation: 53246

You need to first create an array for timeLogDetails, and then push in data to it.

For example:

var timeLogDetails = [ ];

$('.time_input').each(function(i, obj) {

    timeLogDetails.push( {  
        'time': $(this).val(),
        'timeLog': $(this).attr('timelog')
    } ); 

});

Now, you may access the information using:

timeLogDetails[0]['time'] or timeLogDetails[0].time

Upvotes: 3

Related Questions