user1311784
user1311784

Reputation: 345

iterate array to add values to slideshow

This works, but if the array is big, is annoying put all keys $arr[0], $arr[1], and so on.

$arr = shuffleArray(photos);

$.slideshow('slideshow', {
    backgrounds: [{
        src: $arr[0]
      }, {
        src: $arr[1]
      }
    ]
  })

So, i need something like this, but there is something wrong because the slideshow stops working and JS console is empty.

function slideshow() {
  $arr = shuffleArray(photos);
  $.slideshow('slideshow', {
      backgrounds: [
        $.each($arr, function (key, value) {
            {
              src: value
            }
          })
      ]
    })
};  

Upvotes: 1

Views: 60

Answers (2)

Sushanth --
Sushanth --

Reputation: 55750

backgrounds: [
        $.each($arr, function (key, value) {
            {
              src: value
            }
          })
      ]

expects an array of objects

So you need to wrap it up in a function that returns the value in that format.

$arr = shuffleArray(photos);

$.slideshow('slideshow', {
    backgrounds: (function () {
        var temp = [];
        $.each($arr, function (key, value) {
            temp.push({
                src: value
            });
        });
        return temp;
    })()
})

Check Demo Fiddle

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388346

You can use $.map() to transform an array from one format to another

$arr = shuffleArray(photos);
var $srcs = $.map($arr, function(val, index){
    return {
        src: val
    }
})

$.slideshow('slideshow', {
    backgrounds: $srcs
})

Upvotes: 1

Related Questions