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
-
Can you provide the associated HTML?Jason McCreary– Jason McCreary2011年06月06日 14:37:29 +00:00Commented Jun 6, 2011 at 14:37
3 Answers 3
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
Gabriele Petrioli
197k35 gold badges276 silver badges331 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
maerics
158k47 gold badges277 silver badges299 bronze badges
4 Comments
John Strickler
Remember to use .get() at the end to retrieve the raw array then assign it to a variable.
maerics
@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.John Strickler
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").
maerics
@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...var ImageArray = [];
$('div.images').children('img').each( function() {
ImageArray.push({ image: this.src }) // or $(this).attr('src')
} );
answered Jun 6, 2011 at 14:36
Z. Zlatev
4,8101 gold badge35 silver badges39 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-js