1

How can I use jquery to loop though my images & create an array using the "title" & "src" values?

This is my list of images:

<div id="myImages">
  <img data-title="1" src="1.jpg" alt="">
  <img data-title="2" src="2.jpg" alt="">
  <img data-title="3" src="3.jpg" alt="">
  <img data-title="4" src="4.jpg" alt="">
</div>

This is what I need my array to be:

[ { "title" : "1", "image" : "1.jpg", }, { "title" : "2", "image" : "2.jpg", }, { "title" : "3", "image" : "3.jpg", }, { "title" : "4", "image" : "4.jpg", } ]
1
  • Just fyi, an array of arrays looks like this: [[1,2,3],[2,3,4],[2,34,55]], not [{1,2,3},{2,3,4},{2,34,55}]. Commented Feb 11, 2014 at 8:50

3 Answers 3

4

Use .map() convert a set of dom elements to a different representation

var array = $('#myImages img').map(function () {
    var $this = $(this);
    return {
        title: $this.data('title'),
        image: $this.attr('src')
    }
}).get();

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

var data = [];

$('#myImages img').each(function() {
    var img = {title: $(this).data('title'), image: $(this).attr('src')};
    data[data.length] = img;
});

Comments

1
var imageArray = [];
$('#myImages img').each(function() {
  imageArray.push({title: $(this).data('title'), image: $(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.