如何在normalizrJS中应用arrayOf('schema')之前展平数组

时间:2016-03-06 23:19:10

标签: javascript normalizr

假设一个用户已经收藏了许多猫,当被要求提供用户的收藏时,api端点会给出一个猫列表:

const catsList = [{id:1,name:"catA"},{id:2,name:"catB"},{id:3,name:"catC"}];

// ex: GET http://app.com/api/favorites =>  results in following json
{favorites:[{id:2,name:"catB"},{id:3,name:"catC"}]} 
// the result is the list of cats 

//and normalizr schema 
const cats = new Schema('cats');
const favorites = new Schema('favorites');

现在我的问题是,我将如何规范化这些实体,以便我得到以下结果,

  entities.favorites=[2,3]; //2 and 3 are cats
  entities.cats=[{id:1,name:"a"},{id:2,name:"b"},{id:3,name:"c"}];

我将如何使用normalizr完成此操作?

1 个答案:

答案 0 :(得分:0)

这样的东西
const cats = new Schema('cats');

const response = {
  favorites: [{
    id: 2,
    name: "catB"
  }, {
    id: 3,
    name: "catC"
  }]
}

const normalized = normalize(response, {
  favorites: arrayOf(cats)
})

normalized值将类似于

{
  result: {
    favorites: [2, 3]
  },
  entities: {
    cats: {
      2: {
        id: 2,
        name: "catB"
      }, {
        id: 3,
        name: "catC"
      }
    }
  }
}

normalized.entities是一个对象而不是一个数组实际上非常重要 - 否则按ID查询会很慢。

此时,无论如何,您都可以随意转换此表示形式。