Vento Aureo
Vento Aureo

Reputation: 25

Generate image tags from an array of objects

That's my variable:

var images=[{"src":"1.jpg","type":"land"},{"src":"2.jpg"},{"src":"3.jpg"},{"src":"4.jpg"}]

I want to use it to generate image tags on a div, using src as data-src and type as class, like this:

<img data-src="1.jpg" class="land" /><img data-src="2.jpg" /><img data-src="3.jpg" /><img data-src="4.jpg" />

I know how to do it with strings, but not with objects. Can anyone help me with this?

Upvotes: 0

Views: 40

Answers (2)

OrMoush
OrMoush

Reputation: 205

Check this:

 var images = [{"src": "1.jpg", "type": "land"}, {"src": "2.jpg"}, {"src": "3.jpg"}, {"src": "4.jpg"}];
 for (var i = 0; i < images.length; i++) {
    var currentImage = images[i];
    var img = $('<img id="dynamic' + i + '">');
    img.attr('src', currentImage.src);
    if(currentImage.type) {
        img.attr('class',currentImage.type);
    }
    img.appendTo('div');
 }

JSFiddle

Upvotes: 1

jcubic
jcubic

Reputation: 66590

You can try this:

var images=[{"src":"1.jpg","type":"land"},{"src":"2.jpg"},{"src":"3.jpg"},{"src":"4.jpg"}];

$('div').html(images.map(function(obj) {
   var result = '<img data-src="' + obj.src + '"';
   if (obj.type) {
       result += ' class="' + obj.type + '"';
   }
   return result + '/>';
}).join(''));

Upvotes: 0

Related Questions