javascript - 如何构造这个数组,分离类别和产品
问题描述
我有单个数组,我想将类别和类别产品分开
const product = [{
id: 1,
name: 'Cloth',
cat: ['fashion', 'man', 'women']
}, {
id: 2,
name: 'Shoes',
cat: ['fashion']
}, {
id: 3,
name: "hat",
cat: ['man', 'fashion']
}]
如何从产品数组中分离类别值。
const cat = ['fashion','man','women']
如何区分类别和产品
const result = [{
cat: 'fashion',
[{
id: 1,
name: 'Cloth'
}, {
id: 2,
name: 'Shoes'
}, {
id: 3,
name: "hat"
}]
}, {
cat: 'man',
[{
id: 1,
name: 'Cloth'
}, {
d: 3,
name: "hat"
}]
}, {
cat: 'women',
[{
id: 1,
name: 'Cloth'
}]
}]
如何开发这种类型的数组请帮助我。有谁知道请帮帮我,提前坦克回复
解决方案
如果您要从产品数组中获取所有类别。
let allCategories = [];
product.forEach(p => {
allCategories.push(...p.cat);
});
allCategories = [...new Set(allCategories)];
对于第二个问题,我将使用第一个问题的结果:
allCategories.forEach(categorie => {
result.push(
{
cat: categorie,
products : product.filter(p => {
if(p.cat.includes(categorie)) {
return {
id : p.id,
name : p.name
}
}
})
}
)
})
推荐阅读
- syntax-error - 错误 (10500):quartus (VHDL) 中的 VHDL 语法错误
- algorithm - 如何将嵌套大括号递归扩展为笛卡尔积
- c# - 在 blazor webassembly 中使用 ping 类
- excel - 从动态工作表名称中将信息拉入新工作簿
- twitter-bootstrap - 用于在父容器底部定位 div 的引导间距实用程序 (mt-auto) 不工作
- jquery - Keycloak Spring Boot 适配器和 Ajax 请求
- fedora - /var/tmp/rpm-tmp.t40hoV (%build) 的错误退出状态 - Mesa
- excel - 请帮助改进我的 VBA 代码以从 Outlook 电子邮件中提取 excel 附件,并将 excel 文件放入我桌面上的特定文件夹中
- php - 在 json_encode($json, JSON_UNESCAPED_SLASHES) 中转义 css 类的方法
- python - Prometheus 函数装饰器,带有在运行时初始化的标签