Mayeenul Islam Mayeenul Islam - 5 months ago 5x
Javascript Question

Making objects inside an array using plain javascript/jquery

I'm making a WordPress theme, using Vegas for a background slider. First of all, with hard coded image path, I made the slider working. Now I'm trying to make it dynamic.

Vegas doesn't support HTML data attributes, so I need to follow their JS syntax. The syntax of Vegas for declaring slides are like below:

slides: [
{ src: '/img/slide1.jpg' },
{ src: '/img/slide2.jpg' },
{ src: '/img/slide3.jpg' },
{ src: '/img/slide4.jpg' }

The issue is, I'm getting my slider images using PHP query, and getting the exact size of those images using
. So I'm making an array of those images, and the PHP function returns:

Array ( [0] => http://localhost/oneproject/wp-content/uploads/2016/05/slider-image-1200x260.jpg [1] => http://localhost/oneproject/wp-content/uploads/2016/05/disabled-allowance-870x260.jpg )

So I'm passing them using
json_encode( my_array_func() )

file I'm getting this:

var slider_images = JSON.parse( one.slider_images );

The console outputs the following:
console output

I'm struggling now, how can I use this JSON array and use it for Vegas with their given syntax?

I tried (may be looked like amateurish):

slides: [

$.each(slider_images, function( index, value ) {
{ src: "'"+ value +"'" } + ","


But it's not loading the images, and the slider is not working.

I also tried making JS Object within an array:

var myObject = new Object();
myObject.src = slider_images;
$.each(slider_images, function( index, value ) {
myObject.src = value;
var myString = JSON.stringify(myObject);

But getting the first one nice, but the second one got double quotes around, and not working.

I'm completely stuck. Any assistance would be highly appreciated.


You are using this right.

var slider_images = JSON.parse( one.slider_images );

What you can do is this.

First, create a new array where you will store the data-compatible objects.

var newArray = []

Next is loop through each of the slider images and create an object which you will push in the newArray above.

slider_images.forEach(function(e, i){
    var newData = {
        src: e

Then finally, use the newly created array in the slider.

    slides: newArray

Let me know if this works.