javascript - 如何通过 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" }
解决方案
无需为此使用 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) )
推荐阅读
- python - 根据先前的值对 pandas 数据框中的值进行分类
- hyperledger - Hyperledger Indy:什么是受托人和管家?
- three.js - 在增强现实中的应用
- python - SyntaxError:可迭代解包不能用于理解。问题是什么?
- django - 如何仅限制在 Django 频道中显示新消息框
- java - 在我的 Java 程序中读取第二个用户输入不起作用
- spring - NoSuchBeanDefinitionException - SpringBoot 自动装配构造函数包含具有未生成的自动装配声明的参数
- heroku - 为什么没有免费的测功机使用更新?
- regex - 我可以执行“非全局”grep 并仅捕获为每行输入找到的第一个匹配项吗?
- google-chrome - CSS 网格动画在 Chrome 中不起作用