我试图将'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);
但是它不起作用,因为它仅显示图像的最后一个来源
答案 0 :(得分:2)
您可以使用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; }
答案 1 :(得分:0)
您可以使用foreach循环遍历JSON对象。 JSON对象的工作方式与数组不同,因此无法使用OBJECT_NAME [i]遍历它。
您可以执行以下操作:
Object.keys(OBJECT_NAME).forEach(function(key){
console.log(OBJECT_NAME[key]);
});
您还可以对多维对象使用嵌套的foreach循环。我不知道这是否是最好的做法,但这是一个解决方案。