标准化对象数组

时间:2019-05-15 22:08:35

标签: javascript normalizr

我第一次使用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] ] } ?

1 个答案:

答案 0 :(得分:1)

不知道如何在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;
}, {});

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