我尝试将“image”变量更改为具有相同值的 3 个变量“small”、“medium”、“big”。
旧 JSON:
[
{
"name": "nameimage1",
"Images": [ {"image":"1.jpg"}, {"image":"2.jpg"}, {"image":"3.jpg"} ]
},
{
"name": "nameimage2",
"Images": [ {"image":"4.jpg"}, {"image":"5.jpg"}, {"image":"6.jpg"} ]
}
]
我想像这样更改 JSON :
[
{
"name": "nameimage1",
"Images": [ {"small":"1.jpg","medium":"1.jpg","big":"1.jpg"},
{"small":"2.jpg","medium":"2.jpg","big":"2.jpg"},
{"small":"3.jpg","medium":"3.jpg","big":"3.jpg"} ]
},
{
"name": "nameimage2",
"Images": [ {"small":"4.jpg","medium":"4.jpg","big":"4.jpg"},
{"small":"5.jpg","medium":"5.jpg","big":"5.jpg"},
{"small":"6.jpg","medium":"6.jpg","big":"6.jpg"} ]
}
]
我正在尝试像这样使用 for 循环:
function getrealJSON() {
fetch('text/realgallery.json').then((res) => res.json())
.then((data) => {
console.log(data)
var gallery = [];
var album = {};
var albums = [];
var pic = {};
for (let a = 0; a < data.length; a++) {
// console.log(data[a].Images)
console.log(data[a].name)
for (let i = 0; i < data[a].Images.length; i++) {
pic['big'] = pic['medium'] = pic['small'] = data[a].Images[i];
album['Images'] = pic;
albums.push(album);
}
}
console.log(albums);
但这不起作用,因为它只显示最后的图像来源
最佳答案
您可以使用 Images
属性迭代对象并映射新对象。
var data = [{ name: "nameimage1", Images: [{ image: "1.jpg" }, { image: "2.jpg" }, { image: "3.jpg" }] }, { name: "nameimage2", Images: [{ image: "4.jpg" }, { image: "5.jpg" }, { image: "6.jpg" }] }];
data = data.map(o => Object.assign(
{},
o,
{ Images: o.Images.map(({ image }) => ({ small: image, medium: image, big: image })) }
));
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何将 JSON 变量更改为 3 个具有相同值的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53852893/