我需要构建一个JSON字符串来传递我已经由其他javascript函数加载的图像列表
var data = [
{
image: 'image1.jpg'
},
{
image: 'image2.jpg'
},
{
image: 'image3.jpg'
}
];
通过javascript,我可以创建一个JS对象,但据我所知,我需要使用一个键
gallimg = {};
gallimg[1] = {
image: "image1.jpg"
};
gallimg[2] = {
image: "image2.jpg"
};
gallimg[3] = {
image: "image3.jpg"
};
var gallimgjson = JSON.stringify(gallimg, null, 2);
结果是:
{
"1": {
"image": "image1.jpg"
},
"2": {
"image": "image2.jpg"
},
"3": {
"image": "image3.jpg"
}
}
gallimg
需要是一个数组,数组从索引 0 开始,而不是 1
var gallimg = [];
gallimg[0] = { image: "image1.jpg"};
gallimg[1] = { image: "image2.jpg"};
gallimg[2] = {image: "image3.jpg"};
干式解决方案
var images = ["image1.jpg", "image2.jpg", "image3.jpg"];
var gallimg = images.map(function (imageName) {
return {'image': imageName};
});
console.log(JSON.stringify(gallimg, undefined, 4));
的结果
[
{
"image": "image1.jpg"
},
{
"image": "image2.jpg"
},
{
"image": "image3.jpg"
}
]
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;
}