0

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...
}

3 Answers 3

1

This should be the simplest solution:

var imgs = {};

$('.img').each(function(index) {
    imgs['img' + index] = {
        src: src,
        otherProp: ...
        ...
    };
});
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, this was great. Thanks!
1

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

Comments

0

Try:

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

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.