Junior
Junior

Reputation: 12002

How to loop over an array of arrays using jQuery?

I have an array of arrays. I want to be able to loop over each array and for every array I want to add new keys or update existing values.

Here is what I have

    var values = [];

    values['123'] = [];
    values['456'] = [];
    values['123']['x1'] = 'value 1';
    values['123']['x2'] = 'value 2';

I want to loop over the values array, and add new keys to the array for each array. (I.e values['123'] and values['456'])

Here is what I tried

$.each(values, function(index, value){

  value['x1'] = 'new value 1';
  value['x10'] = 'new value 10';
  value['x20'] = 'new value 20';
  console.log(value);

});

The console shows this error

TypeError: value is undefined

Here is a fiddle

How can I correcly loop over each array item and update the original array?

Upvotes: 3

Views: 230

Answers (2)

isvforall
isvforall

Reputation: 8926

Actually for your case you need to use Object, not Array

For constructing non-numeric indexes you should use {}

{} - for constructing Object, [] - for constructing Array

jQuery.each() can be used to iterate over both objects and arrays.

Try this code

$(function() {
    $('#x').click(function(e) {
        var values = {}; // here

        values['123'] = {}; // here
        values['456'] = {}; // here
        values['123']['x1'] = 'value1';
        values['123']['x2'] = 'value2';


        $.each(values, function(index, value) {

            value['x1'] = 'new value 1';
            value['x10'] = 'new value 10';
            value['x20'] = 'new value 20';
            console.log(value);

        });
    });
});

Upvotes: 1

Shekhar Chikara
Shekhar Chikara

Reputation: 3822

This is happening because your values array is getting initialized with indexes 123 and 456. So, the $.each() function assumes the array length to be 457 and thus starts from element index 0, though there is no value at that index.

In order to overcome this, you can simply make the following change and it will work-

$.each(values, function(index, value){
    if(values[index] !== undefined) { 
        value['x1'] = 'new value 1';
        value['x10'] = 'new value 10';
        value['x20'] = 'new value 20';

        //Update the new values in the values object.
        values[index] = value;
        console.log(value);
    }
});

Upvotes: 0

Related Questions