gpt4 book ai didi

javascript - 如何将 JSON 变量更改为具有相同值的 3 个变量?

转载 作者:行者123 更新时间:2023-11-29 20:47:28 25 4
gpt4 key购买 nike

我试图将“图像”变量更改为具有相同值的 3 个变量“小”、“中”、“大”。

旧 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);

但它不起作用,因为它只显示最后一个图像源

我的结果:please see my result image

最佳答案

您可以使用 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/

25 4 0
文章推荐: javascript - react VX 图表 : React does not recognize the `xScale` prop on a DOM element
文章推荐: android - 如何在 Appcompat 22 中从汉堡包图标动态更改为向上图标
文章推荐: android - 当我的应用程序在后台运行时,如何让 android 系统杀死我的应用程序?
文章推荐: php - 基于