Search code examples
javascriptjsongalleria

Build a JSON string for galleria in javascript


I need to build a JSON string to pass a list of image that I already load by an other javascript function

var data = [
{
    image: 'image1.jpg'
},
{
    image: 'image2.jpg'
},
{
    image: 'image3.jpg'
}
];

Via javascript I can create a JS object, but I need to use a key, as far as I know

gallimg = {};

gallimg[1] = {
    image: "image1.jpg"
};

gallimg[2] = {
    image: "image2.jpg"
};

 gallimg[3] = {
    image: "image3.jpg"
};

var gallimgjson = JSON.stringify(gallimg, null, 2);

Result is:

{
  "1": {
    "image": "image1.jpg"
  },
  "2": {
    "image": "image2.jpg"
  },
  "3": {
    "image": "image3.jpg"
  }
}

Solution

  • gallimg needs to be an array, and an array starts from index 0, not 1

    var gallimg = [];
    
    gallimg[0] = { image: "image1.jpg"};
    
    gallimg[1] = { image: "image2.jpg"};
    
    gallimg[2] = {image: "image3.jpg"};
    

    DRY Solution

    var images = ["image1.jpg", "image2.jpg", "image3.jpg"];
    
    var gallimg = images.map(function (imageName) {
        return {'image': imageName};
    });
    

    Result of console.log(JSON.stringify(gallimg, undefined, 4));

    [
        {
            "image": "image1.jpg"
        },
        {
            "image": "image2.jpg"
        },
        {
            "image": "image3.jpg"
        }
    ]