javascript - JS normalizr 如何向实体添加不相关的键

标签 javascript redux normalizr

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

关于javascript - JS normalizr 如何向实体添加不相关的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44180692/

相关文章:

javascript - normalizr 模式中的嵌套数组

javascript - 如何重复动态增加div(div在顶部和div在底部)

javascript - 是否可以在 javascript 中检测表单提交失败?

reactjs - React Redux - this.props.actions.fetchPosts 不是函数

javascript - 在 Normalizr 模式中设置深度关联

Redux + Normalizr : Adding and deleting normalized entities in Redux state

javascript - 如何使用 jquery 将字符串中的数字增加一个

javascript - 如何使用javascript在html中添加、删除div或span?

javascript - React redux 连接渲染优化

javascript - 根据值数组中的值删除对象数组中的对象 - Javascript