Notes

Converting Arrays into Objects for easily finding values by key

Edit on GitHub

JavaScript
2 minutes

What i have:

An array of objects. An object contains an id that is a number corresponding to a name that is a string. The array defines movie genres that are returned by TMDB API.

This array of objects is difficult to get values from. If i want to get the name of a genre by id, i have to loop over the entire array to find that value.

 1const genresArray = [
 2    {
 3      id: 28,
 4      name: 'Action',
 5    },
 6    {
 7      id: 12,
 8      name: 'Adventure',
 9    },
10    {
11      id: 16,
12      name: 'Animation',
13    },
14    {
15      id: 35,
16      name: 'Comedy',
17    },
18    {
19      id: 80,
20      name: 'Crime',
21    },
22    {
23      id: 99,
24      name: 'Documentary',
25    },
26    {
27      id: 18,
28      name: 'Drama',
29    },
30    {
31      id: 10751,
32      name: 'Family',
33    },
34    {
35      id: 14,
36      name: 'Fantasy',
37    },
38    {
39      id: 36,
40      name: 'History',
41    },
42    {
43      id: 27,
44      name: 'Horror',
45    },
46    {
47      id: 10402,
48      name: 'Music',
49    },
50    {
51      id: 9648,
52      name: 'Mystery',
53    },
54    {
55      id: 10749,
56      name: 'Romance',
57    },
58    {
59      id: 878,
60      name: 'Science Fiction',
61    },
62    {
63      id: 10770,
64      name: 'TV Movie',
65    },
66    {
67      id: 53,
68      name: 'Thriller',
69    },
70    {
71      id: 10752,
72      name: 'War',
73    },
74    {
75      id: 37,
76      name: 'Western',
77    },
78  ]

What i want:

An object with the id as key.

 1{
 2  28: 'Action',
 3  12: 'Adventure',
 4  16: 'Animation',
 5  35: 'Comedy',
 6  80: 'Crime',
 7  99: 'Documentary',
 8  18: 'Drama',
 9  10751: 'Family',
10  14: 'Fantasy',
11  36: 'History',
12  27: 'Horror',
13  10402: 'Music',
14  9648: 'Mystery',
15  10749: 'Romance',
16  878: 'Science Fiction',
17  10770: 'TV Movie',
18  53: 'Thriller',
19  10752: 'War',
20  37: 'Western',
21}

And here is how we’d do it in TypeScript

1interface GenresObject {
2  [index: number]: string
3}
4let genresObject: GenresObject = {}
5
6genresArray.map(genre => {
7  genresObject[genre.id]: genre.name
8})

This shape of the object makes it very easy to get a genre name by id. For example:

1console.log(genresObject.10770) // 'TV Movie'