3

我正在规范一个一级嵌套的批次列表。第一级地块被称为主人,嵌套的地块是奴隶。

// my schema
const lot = new schema.Entity('lots');
const lots = new schema.Array(lot);
lot.define({slaves: lots});

// my data
const list = [
  {
    id: 1,
    name: 'Lot #1',
    slaves: [
      {
        id: 2,
        name: 'Lot #2'
      }
    ]
  }, {
    id: 4,
    name: 'Lot #4',
    slaves: []
  }
];

normalize(list, lots);

我明白了:

{
  entities : {
    lots: {
      '1': {
        id: 1,
        name: 'Lot #1',
        slaves: [2]
      },
      '2': {
        id: 2,
        name: 'Lot #2'
      },
      '4': {
        id: 4,
        name: 'Lot #4',
        slaves: []
      }
    }
  },
  result : [1, 4]
}

它有什么问题。但我想在标准化结果中添加更多内容,但我不知道如何。

  • 在规范化的奴隶上拥有主批次 id
  • 结果中还有一个从属 ID 数组

所以前面的例子会像这样标准化:

{
  entities : {
    lots: {
      '1': {
        id: 1,
        name: 'Lot #1',
        slaves: [2]
      },
      '2': {
        id: 2,
        name: 'Lot #2',
        master: 1
      },
      '4': {
        id: 4,
        name: 'Lot #4',
        slaves: []
      }
    }
  },
  result : {
    masters: [1, 4],
    slaves: [2],
  }
}

normalizr 可以做到这一点吗?

4

1 回答 1

2

在规范化的奴隶上拥有主批次 id

这绝对可以使用自定义processEntity函数。这里有一个例子。简而言之:

const processStrategy = (value, parent, key) => ({
  ...value,
  master: key === 'slaves' ? parent.id : undefined
});
const lot = new schema.Entity('lots', { processStrategy });

结果中还有一个从属 ID 数组

这是不可能的。result总是依赖于传递给的条目模式normalize

于 2017-01-12T17:25:50.560 回答