holyredbeard
holyredbeard

Reputation: 21288

Creating an object with several properties through each loop

It's been awhile since I worked with objects so I need to refresh my memory. What I need help with is how to create an object in an each loop with several properties. Below is what I've tried so far but that's obviously not correct.

var imgs = {},
    i = 0;

$('.img').each(function() {
    i++;

    imgs['img' + i]['src'] = src;  // doesn't work

    // imgs['img' + i] = src; <- works but I want several properties for every image.
});

desired output:

imgs: {
    img1: {
        src: 'http://...',
        otherProp: '...'
    },
    img2: {
        src: 'http://...',
        otherProp: '...'
    },
    and so on...
}

Upvotes: 0

Views: 27

Answers (3)

Suman Bogati
Suman Bogati

Reputation: 6351

You should create a new object with imgs['img' + i] = {}; and set the src property and it's value to that object.

something like

$('.img').each(function() {
    i++;
    imgs['img' + i] = {};  //on each iteration created the new object
    imgs['img' + i]['src'] = src;  
});

Upvotes: 1

bingjie2680
bingjie2680

Reputation: 7773

This should be the simplest solution:

var imgs = {};

$('.img').each(function(index) {
    imgs['img' + index] = {
        src: src,
        otherProp: ...
        ...
    };
});

Upvotes: 1

deviloper
deviloper

Reputation: 7240

Try:

imgs['img' + i]['src'] = $(this).attr('src');

Upvotes: 0

Related Questions