1

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');
  });
1
  • 1
    You need to create object instead of an array like this. Commented Dec 16, 2014 at 9:54

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

But now je is missing the i. He want set the time and the timelog for a specific index i think.
@hamala94 No, he doesn't. i will always be a numerical index starting at 0. Since the array (or object in his case) is empty to begin with, the code I posted above produces the same result as his would (if it worked).
1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.