I have the feeling that this is an obscure side of Javascript that I simply do not know or understand.
I'm retrieving an array of objects from a database using Sequelize. It's a relatively complex array, as in contains associations. The array looks like this (it is simplified) :
[
{
name: '...',
director: '...',
genres: [
{id: 1, name: 'Mystery'},
{id: 2, name: 'Thriller'},
],
},
...
]
I want to map this array so to change the format of genres
from this:
genres: [
{id: 1, name: 'Mystery'},
{id: 2, name: 'Thriller'},
],
to this:
genres: ['Mystery', 'Thriller'],
So I did something which I believe is quite common in Javascript :
movies.map((movie) => {
movie.genres = movie.genres.map(g => g.name);
movie.actors = movie.actors.map(a => a.name);
return movie;
});
console.log(JSON.stringify(movies));
However, once printed to the console, the array is completely unchanged. To have the desired effect on this array, I had to convert it into a string of characters and back into an array before performing the map()
operations, like so:
movies = JSON.parse(JSON.stringify(movies));
movies.map((movie) => {
movie.genres = movie.genres.map(g => g.name);
movie.actors = movie.actors.map(a => a.name);
return movie;
});
console.log(JSON.stringify(movies));
Why did it work ? I'm guessing that doing this conversion back and forth removed certain fields from the object, but I do not see how this could've had an effect on the array.
EDIT: using other methods like Array.from
or the spread operator (movies = [...movies]
) does not work.