0

I want to make array like this

var ImageArray = [
 {image:"/image1.jpg"},
 {image:"/image1.jpg"},
 {image:"/image1.jpg"}
 ]

I want to make above structure of array from div containing images using each function of jquery.

so that I can retrieve it like ImageArray[index].image

asked Jun 6, 2011 at 14:33
1
  • Can you provide the associated HTML? Commented Jun 6, 2011 at 14:37

3 Answers 3

6
var ImageArray = [];
$('div img').each(function(){
 ImageArray.push({image:this.src});
});

this div part of the selector should be altered to match the div you want to use as the container..

answered Jun 6, 2011 at 14:38
Sign up to request clarification or add additional context in comments.

Comments

1

You can also use jQuery.map() to do it in a single call, without having to declare a separate array, e.g.:

var ImageArray = $('div img').map(function(i,img) {
 return {image:this.src};
});
answered Jun 6, 2011 at 14:40

4 Comments

Remember to use .get() at the end to retrieve the raw array then assign it to a variable.
@John Strickler, no need to use get() in this case since map returns an array of the objects returned by the callback function. But the assignment is a good idea, that makes the intent a little more clear.
I thought it was an array wrapped in a jQuery object? I may be wrong but I believe .get() will return the actual array ("unwrapping it").
@John Strickler: hmm, after testing it does appear that the returned array has a "get" method which "returns a 'clean' array" (as opposed to a jQuery tainted one?) so I guess using get() is fine but not strictly necessary. I wonder what the pros/cons of that are...
0
var ImageArray = [];
$('div.images').children('img').each( function() {
 ImageArray.push({ image: this.src }) // or $(this).attr('src')
} );
answered Jun 6, 2011 at 14:36

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.