0

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"
  }
}
Prince Agrawal
  • 3,619
  • 3
  • 26
  • 41
al404IT
  • 1,380
  • 3
  • 21
  • 54

2 Answers2

1

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"
    }
]
dcodesmith
  • 9,590
  • 4
  • 36
  • 40
0
var data = [];

// possible loop?
data.push(imageOBJ('image1.jpg'));
data.push(imageOBJ('image2.jpg'));
data.push(imageOBJ('image3.jpg'));
var JSONData = JSON.stringify(data, null, 2);

function imageOBJ(fileName){
  var self = this;
  self.image = fileName;
  return self;
}
Calvin
  • 181
  • 12