Reputation: 1519
I'm using the normalizr
library for the first time, had no idea this existed
I have a JSON response that looks like this:
{
"Action": [
{
"id": "cbbe648e-123c-4a2c-a1a2-22d5f51151b0",
"title": "Cold Pursuit",
"poster_url": "https://image.tmdb.org/t/p/original/otK0H9H1w3JVGJjad5Kzx3Z9kt2.jpg"
},
...
{
"id": "0efa59d8-6700-4f91-82bf-a38682f1f1b4",
"title": "Hellboy",
"poster_url": "https://image.tmdb.org/t/p/original/bk8LyaMqUtaQ9hUShuvFznQYQKR.jpg"
}
],
"Adventure": [
{
"id": "da8508a5-3b03-49f9-9e75-31ded0d4f68c",
"title": "Dumbo",
"poster_url": "https://image.tmdb.org/t/p/original/279PwJAcelI4VuBtdzrZASqDPQr.jpg"
...
{
"id": "f4b14d2e-339f-40b2-b416-9c88297941ad",
"title": "Avengers: Endgame",
"poster_url": "https://image.tmdb.org/t/p/original/or06FN3Dka5tukK1e9sl16pB3iy.jpg"
},
]
}
I want to essentially use normalizr to get an array of all the movies (the objects within each genre) I have this as my schema, and two selectors working:
import { schema } from 'normalizr';
export const movie = new schema.Entity('movies');
export const genre = { movies: [movie] };
export const feed = { moviesByGenre: [genre], upcoming: [movie] };
export const selectMovieId = { movieId: // [ genre: [movies] ] } ?
Upvotes: 0
Views: 328
Reputation: 1658
Not sure how to do this in normalizr, but in plain old Javascript you can do something like:
// Get a list of just the movies
var moviesList = [].concat.apply([], Object.values(movie));
// Get an object mapping movie keys to movie objects
var moviesById = moviesList.reduce(function(result, movie) {
result[movie['id']] = movie;
return result;
}, {});
If that does what you're looking for, please let me know and I can explain each line in more depth.
Upvotes: 1