规范化对象数组

Normalizing an array of objects

我是第一次使用 normalizr 库,不知道它存在 我有一个 JSON 回复,看起来像这样:

{
  "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"
    },
  ]
}

我想基本上使用 normalizr 来获取所有电影的数组(每个类型中的对象) 我将此作为我的模式,并且有两个选择器在工作:

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] ] } ?

不确定如何在 normalizr 中执行此操作,但在普通的旧 Javascript 中,您可以执行以下操作:

// 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;
}, {});

如果这符合您的要求,请告诉我,我可以更深入地解释每一行。