首页 > 解决方案 > 如何通过 normalizrjs 规范化 javascript 中的数据?

问题描述

我有三个对象:类别、子类别、文章。他们之间的关系是通过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 },
]

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

我需要像这样访问引用对象值的底线:

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" }

标签: javascriptnormalizationnormalizr

解决方案


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


推荐阅读