Velibor Nikolic Velibor Nikolic - 1 year ago 56
Javascript Question

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.

Answer Source

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);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download