Array.prototype.reduce()便利
たとえば下記の外部APIから配列を受け取る
https://picsum.photos/v2/list?page=1&limit=10
[
{
"id": "0",
"author": "Alejandro Escamilla",
"width": 5616,
"height": 3744,
"url": "https://unsplash.com/photos/yC-Yzbqy7PY",
"download_url": "https://picsum.photos/id/0/5616/3744"
},
/* 中略 */
{
"id": "1005",
"author": "Matthew Wiebe",
"width": 5760,
"height": 3840,
"url": "https://unsplash.com/photos/tBtuxtLvAZs",
"download_url": "https://picsum.photos/id/1005/5760/3840"
}
]
この配列を下記のような配列に整形したい
[
{
id: "0",
maxWidth: 5616,
maxHeight: 3744,
src: "https://unsplash.com/photos/yC-Yzbqy7PY",
},
{
id: "1005",
maxWidth: 5760,
maxHeight: 3840,
src: "https://unsplash.com/photos/tBtuxtLvAZs",
}
]
Array.prototype.reduce() 便利
const rt = array.reduce((acc,cur,idx)=>{
const { id, width, height, url } = cur;
acc[idx] = {
id,
maxWidth: width,
maxHeight: height,
src: url,
}
return acc;
},[])
/// console.log(rt)
[
{
"id": "0",
"maxWidth": 5616,
"maxHeight": 3744,
"src": "https://unsplash.com/photos/yC-Yzbqy7PY"
},
/* 中略 */
{
"id": "1005",
"maxWidth": 5760,
"maxHeight": 3840,
"src": "https://unsplash.com/photos/tBtuxtLvAZs"
}
]
最高、、、
参考
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce