如何通过normalizrjs标准化javascript中的数据?

时间:2019-05-23 16:13:34

标签: javascript normalization normalizr

我有三个对象:类别,子类别,文章。它们之间的关系是按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" }

1 个答案:

答案 0 :(得分:0)

无需为此使用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)  )