Baklap4
Baklap4

Reputation: 4202

$.each() over Key value pair array

I've created my array as following:

var test = [];
test['pizza'] = 4;
test['pudding'] = 6;

I'm used to use $.each to loop over my array and print out the values and indexes. I'm doing this as following:

$.each(test, function (index, value){
    console.log(value); 
});

Yet somehow it does only print []. How would one loop through an array as mine to print out the values 4 and 6?

Upvotes: 2

Views: 60

Answers (4)

erikvimz
erikvimz

Reputation: 5476

You don't need jQuery to iterate through a Javascript array, just use for.

var test = [];
test['pizza'] = 4;
test['pudding'] = 6;

for (var k in test) {
    if (test.hasOwnProperty(k)) {
        console.log('Key: ' + k + ' Value: ' + test[k]);
    }
}

// Key: pizza Value: 4
// Key: pudding Value: 6

You don't need to declare test as an object for this (suggested in other answers), array is fine.

By using for you are improving performance of your application. See here.

In both Firefox and Chrome, the for loop is well over 100x faster than the others.

Upvotes: 1

Parag Bhayani
Parag Bhayani

Reputation: 3330

Here test is an object(Associative array), not an array so you need to declare it as javascript object

var test = {};
test['pizza'] = 4;
test['pudding'] = 6;

$.each(test, function (index, value){
    console.log(value); 
});

Upvotes: 0

Hrishikesh
Hrishikesh

Reputation: 345

you might want to choose what happens to serve your needs. I guess you were trying to get a array of objects which will look something like [{},{},{},{}]

Upvotes: 0

Tushar
Tushar

Reputation: 87203

each will only iterate over iterable properties of the array, pizza and pudding are not iterable properties.

As you require the key-value pair, declare the variable as object.

var test = {};
test['pizza'] = 4;
test['pudding'] = 6;

Upvotes: 4

Related Questions