我试图从一个复杂的API结构中获取数据。如何从以下对象和数组中获取所有图像:
const x = { cars: [
{ types:
{
name: "VW",
image: [{ url: "http://www.lkjl.com" }]
}
},
{...},
{...}
]};

我知道我可以像这样得到图像url:
x.cars[0].types.image[0].url但是我怎么才能打印出所有的图像urls呢?
x.cars.map(item => {
return(
item.image[0].url; // this is wrong
);
});我需要在map函数中有另一个map吗?
发布于 2017-08-01 19:40:37
您可以通过映射url属性来使用Array#reduce。
const
x = { cars: [{ types: { name: "VW", image: [{ url: "http://www.lkjl.com" },{ url: "http://www.alkjl.com" }] } }, { types: { name: "Tata", image: [{ url: "http://www.lskal.com" },{ url: "http://www.lkfjl.com" }] } }] },
images = x.cars.reduce((r, item) => r.concat(item.types.image.map(i => i.url)), []);
console.log(images);
发布于 2017-08-01 19:37:44
我想你错过了types
x.cars.map(item => {
return(
item.types.image[0].url;
);
});发布于 2017-08-01 19:38:54
我想你在map函数中没有访问到‘type’对象,它应该是这样的:
x.cars.map(item => {
return(
item.types.image[0].url; //this should work for you
);
});https://stackoverflow.com/questions/45436682
复制相似问题