user2744859
user2744859

Reputation: 37

How to add multiple values in an array

How to add an array dynamically as in the code below. I have created a multi-dimensional array in JavaScript but how do I push src that is "/_layouts/15/SSNIT.Portal/Images/ssnit02.jpg" and title that is "MyTitle". I have multiple values and I am iterating through them?

carousel_images_info = [
    { src: "/_layouts/15/My.Portal/Images/my1.jpg", title: "ssnit01" },
    { src: "/_layouts/15/my3.Portal/Images/my2.jpg", title: "ssnit02" },
    { src: "/_layouts/15/my4.Portal/Images/my3.jpg", title: "ssnit03" },
    { src: "/_layouts/15/my5.Portal/Images/my4.jpg", title: "ssnit04" },
    { src: "/_layouts/15/my5.Portal/Images/ssnit05.jpg", title: "ssnit05" }
];

Upvotes: 0

Views: 129

Answers (4)

user1636522
user1636522

Reputation:

Just push :)

carousel_images_info.push({ 
    title: "MyTitle",
    src: "/_layouts/15/SSNIT.Portal/Images/ssnit02.jpg"
});

However, if you want to avoid duplicates, you'll have to iterate through the entire list to perform a comparison before adding the new row. Another solution could be to push everything then to remove duplicates only when required.

Upvotes: 1

Louis
Louis

Reputation: 1

the value for the src and title is dynamic, so can i do like this?

  var item_enumerator = this.items.getEnumerator();
  while (item_enumerator.moveNext()) {
    var item = item_enumerator.get_current();
    var image_url = location.protocol + "//" + location.host + item.get_item('FileRef');
    var image_title = item.get_item('FileLeafRef'); 
    var set = {
      src: image_url,
      title : image_title
    };
    this.carousel_images_info.push(set);
  }

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try this out,

var new_obj = {};
new_obj.src = "/_layouts/15/SSNIT.Portal/Images/ssnit02.jpg";
new_obj.title= "MyTitle";

carousel_images_info[carousel_images_info.length] = new_obj

So make a function if you are doing this dynamically,

carousel_images_info=[];

function Insert(xSrc,xTitle)
{
    var new_obj = {};
    new_obj.src = xSrc;
    new_obj.title= xTitle;

    carousel_images_info[carousel_images_info.length] = new_obj;
}

Insert("/_layouts/15/SSNIT.Portal/Images/ssnit02.jpg","MyTitle");

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

That is array containing objects, you need to push object to it, like:

var new_obj = {
    src: "/_layouts/15/SSNIT.Portal/Images/ssnit02.jpg",
    title: "My Title"
};
carousel_images_info.push(new_obj);

Upvotes: 1

Related Questions