1

我想用 规范化我的数据normalizr。问题是我的数据中有一个键 ( teams),它与其他数据没有关系。

例如:

const data = {
   programs: [{
       id: 1,
       label: 'Program one',
       products: [{
           id: 1,
           label: 'Product one',
           releases: [{
             id: 1,
             label: 'Release one',
           }]
         }
       ]
     }
   ],
   teams: [{
       id: 1,
       value: 1,
       label: 'Team one',
     }
   ]
 }

我的架构:

  const release = new schema.Entity('releases');

  const product = new schema.Entity('products', {
    releases: [release]
  });

  const program = new schema.Entity('programs', {
    products: [product],
  });

  normalize(data, [program]);

我怎样才能将团队添加到由生成的实体对象中normalizr?所以结果需要是:

{
  entities: {
     products: {},
     programs: {},
     releases: {},
     teams: []
  }
}
4

1 回答 1

2

normalizr如果您告诉它数据的包含模式,则可以处理不相交的数据集:

const release = new schema.Entity('releases');

const product = new schema.Entity('products', {
  releases: [release]
});

const program = new schema.Entity('programs', {
  products: [product],
});

// add team entity
const team = new schema.Entity('teams');

// the encompassing schema
const dataschema = {
  programs: [program],
  teams: [team]
}

// normalize
normalize(data, dataschema);

// or omit dataschema definition and pass in directly
normalize(data, {
    programs: [program],
    teams: [team]
});

将导致:

请注意,该result对象现在由两个数组组成,其中包含顶级实体的键。

{
    entities: {
        releases: {
            1: {
                id: 1,
                label: "Release one"
            }
        },
        products: {
            1: {
                id: 1,
                label: "Product one",
                releases: [1]
            }
        },
        programs: {
            1: {
                id: 1,
                label: "Program one",
                products: [1]
            }
        },
        teams: {
            1: {
                id: 1,
                value: 1,
                label: "Team one"
            }
        }
    },
    result: {
        programs: [1],
        teams: [1]
    }
}
于 2017-05-25T15:30:10.770 回答