Image de l'article 'Extract arrays from objects into a single array'

Extract arrays from objects into a single array

Have you ever needed to put arrays from a list of objects into the single array? JavaScript provides a native API to do it and it’s simple.

It’s simple: use the Array.prototype.flatMap() method along with the object destructuring.

For example, you have this array of objects. Each object contains an array of primitive values:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
"categories": [
    {
      "forums": [
        "-KpOx5Y4AqRr3sB4Ybwj",
        "-KsjO4_W3W9Q2Z2UmuPr"
      ],
      "name": "Feedback & Information",
      "slug": "feedback-and-information",
      "id": "-KpR7vRkiRPpbUd_TVAR"
    },
    {
      "forums": [
        "-KsjPat5MWCx-dkjNVg8",
        "-KsjPjasLh0TFtZmffEo",
        "-Kvd1Vg_ankLYgrxC50F",
        "-KvdCowY9mDvM0EH8Pvs",
        "-KvhkEl6F673igPtnbso"
      ],
      "name": "Discussions",
      "slug": "discussions",
      "id": "-KsjPKA6hDuHlQK_lJWO"
    },
    {
      "forums": [
        "-Kvclvu_Qd9QdS9ciqUl",
        "-KvcmOcppNYK8NCesmB9"
      ],
      "name": "Comedy",
      "slug": "comedy",
      "id": "-KvclpNRjpI5W-j0JQGU"
    }
  ],

If you want to get the forum strings, using object destructuring and flatMap will provide you the solution:

1
const forums = categories.flatMap(({ forums }) => forums);

The result will give you:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
[
  "-KpOx5Y4AqRr3sB4Ybwj",
  "-KsjO4_W3W9Q2Z2UmuPr",
  "-KsjPat5MWCx-dkjNVg8",
  "-KsjPjasLh0TFtZmffEo",
  "-Kvd1Vg_ankLYgrxC50F",
  "-KvdCowY9mDvM0EH8Pvs",
  "-KvhkEl6F673igPtnbso",
  "-Kvclvu_Qd9QdS9ciqUl",
  "-KvcmOcppNYK8NCesmB9"
]

Check out the JSFiddle demo to prove it.

Enjoy!

Credit : Photo by Alev Takil on Unsplash.

License GPLv3 | Terms
Built with Hugo
Theme Stack designed by Jimmy