繁体   English   中英

如何通过normalizrjs规范化javascript中的数据?

[英]How to normalize data in javascript by normalizrjs?

我有三个对象:类别,子类别,文章。 他们之间的关系是由id。

const categories = [
  { id: 1, name: 'category-1' },
  { id: 2, name: 'category-2' },
  { id: 3, name: 'category-3' },
  { id: 4, name: 'category-4' },
];

const subCategories = [
  { id: 1, name: 'sub-category-a', category: 1 },
  { id: 2, name: 'sub-category-b', category: 2 },
  { id: 3, name: 'sub-category-c', category: 1 },
  { id: 4, name: 'sub-category-d', category: 3 },
  { id: 5, name: 'sub-category-e', category: 4 },
]

const articles = [
  { id: 101, name: 'article-x', subCategory: 3 },
  { id: 103, name: 'article-y', subCategory: 1 },
  { id: 108, name: 'article-z', subCategory: 4 },
  { id: 107, name: 'article-r', subCategory: 2 },
  { id: 123, name: 'article-p', subCategory: 2 },
  { id: 142, name: 'article-q', subCategory: 1 },
]

我不确定如何为这些对象定义正确的方案。 normalizr 我也不确定这个包是否会成为解决方案。

我需要访问参考对象值的底线:

console.log({ a: articles[0].subCategory.name }); // should output: { a: "sub-category-c" }
console.log({ a: articles[0].subCategory.category.name }); // should output: { a: "category-1" }

没有必要使用normalizr ...

 const categories = [ { id: 1, name: 'category-1' }, { id: 2, name: 'category-2' }, { id: 3, name: 'category-3' }, { id: 4, name: 'category-4' }, ]; const subCategories = [ { id: 1, name: 'sub-category-a', category: 1 }, { id: 2, name: 'sub-category-b', category: 2 }, { id: 3, name: 'sub-category-c', category: 1 }, { id: 4, name: 'sub-category-d', category: 3 }, { id: 5, name: 'sub-category-e', category: 4 }, ] const articles = [ { id: 101, name: 'article-x', subCategory: 3 }, { id: 103, name: 'article-y', subCategory: 1 }, { id: 108, name: 'article-z', subCategory: 4 }, { id: 107, name: 'article-r', subCategory: 2 }, { id: 123, name: 'article-p', subCategory: 2 }, { id: 142, name: 'article-q', subCategory: 1 }, ] function Get_Article_SubCategorie( Art_id ) { let sc = articles.find(a=>a.id===Art_id).subCategory return subCategories.find(s=>s.id===sc).name; } function Get_Article_Categorie( Art_id ) { let sc = articles.find(a=>a.id===Art_id).subCategory, c = subCategories.find(s=>s.id===sc).id; return categories.find(n=>n.id===c).name; } console.log( Get_Article_SubCategorie(101) ) console.log( Get_Article_SubCategorie(108) ) console.log( Get_Article_Categorie(101) ) console.log( Get_Article_Categorie(108) ) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM