我想用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: []
  }
}

最佳答案

如果您告诉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]
    }
}

09-04 23:29