Velibor Nikolic
Velibor Nikolic

Reputation: 237

Push A List of Objects Into an Array Using jQuery (Or Javascript)

$=jQuery.noConflict();
$( document ).ready(function() {
    //returns an array of image links
    // ["http://velnikolic.com/gallery/wp-content/uploads/2017/04/file4741298583098-1-150x150.jpg", "http://velnikolic.com/gallery/wp-content/uploads/2017/04/file9221293737060-150x150.jpg", "http://velnikolic.com/gallery/wp-content/uploads/2017/04/file4741298583098-150x150.jpg"]
    var images = <?php echo json_encode($images); ?>;
    console.log(images);
    src = [];
    data = {}

    for (var i = 0; i < images.length; i++) {
        data = {
            src: images[i] 
        };

        src.push(data);
        console.log(data);
        //Data should equal [{src : imageurlxxx}, {src :imgurlxxdd}, {src :imgurlxxdd} ]}
    }
});//close

The above code should loop through the images array and push it into an object with src as the key, then it should push this object into an array and reiterate. The problem is that the object is overwritten in the array because they all have the same key.

Upvotes: 0

Views: 4437

Answers (3)

TxRegex
TxRegex

Reputation: 2425

function getImages() {
    var images = <?php echo json_encode($images); ?>;
    return images.map(function (image) {
        return { src: image };
    }
};

Assuming you are using this on a php site and $images is set, getImages() returns something like this:

 [
    {src: "http://velnikolic.com/gallery/wp-content/uploads/2017/04/file4741298583098-150x150.jpg"},
    {src: "http://velnikolic.com/gallery/wp-content/uploads/2017/04/file9221293737060-150x150.jpg"}, 
    {src: "http://velnikolic.com/gallery/wp-content/uploads/2017/04/file4741298583098-150x150.jpg"}
]

Upvotes: 1

Dekel
Dekel

Reputation: 62536

Your code does exactly what you are looking for, but you checked the wrong variable:

var images = ["A", "B", "C"]
console.log(images);
src = [];
data = {}
for (var i = 0; i < images.length; i++) {
  data = {
    src: images[i] 
  };
  // Here data is an object with 1 key only.

  src.push(data);
}
// Here - after the loop - the src variable will contain all of the values that you want.
console.log(src);

And if you are looking for an ES6 solution you can use this one:

var images = ["A", "B", "C"];
var src = images.map((img) => { return {src: img} });
console.log(src);

Upvotes: 6

Taplar
Taplar

Reputation: 24965

//Data should equal [{src : imageurlxxx}, {src :imgurlxxdd}, {src :imgurlxxdd} ]}
data = $.map(images, (image) => { src: image })

If i'm reading what you want right, you just need to map your image urls into the array like you want them.

Upvotes: 0

Related Questions