LoginSignup
0
1

More than 3 years have passed since last update.

Array.prototype.reduce() 便利

Last updated at Posted at 2019-07-30

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

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1