我正在处理 django rest 和 angular 这个 json 数组来自服务器 ic 包含类别和子类别值..
我正在尝试构建一个动态导航栏,所以我想像这样安排这些数据
[
[网络开发] : ["subCat1","subcat2",....]
[安卓开发] : ["subCat1","subcat2",....]
]
访问类别及其相关子类别
我试过这样的事情:但它只设置键和值是空的
public categories = [[], [], [], []];
public data;
for (let i = 0; i < this.data.length; i++) {
if (this.data[i].cat_id != null) {
this.categories[i][this.data[i].title] = [];
}
if (this.data[i].parent_id != null && this.data[i].parent_id == this.data[i].cat_id) {
this.categories[i][this.data[i].title] = [this.data[i].title]
}
}
它的服务器响应
[
{
"id": 5,
"cat_id": 0,
"parent_id": null,
"title": "web development"
},
{
"id": 6,
"cat_id": 1,
"parent_id": null,
"title": "android development"
},
{
"id": 7,
"cat_id": null,
"parent_id": 0,
"title": "php"
},
{
"id": 8,
"cat_id": null,
"parent_id": 1,
"title": "java"
}
]
最佳答案
这里有一些代码可以做你想做的:
interface Categories {
[title: string]: string[]
}
let categories: Categories = {};
data.filter(c => c.parent_id === null).map(c => <{ title: string; subcategories: string[] }>{
title: c.title,
subcategories: data.filter(sc => sc.parent_id === c.cat_id).map(sc => sc.title)
}).forEach(c => {
categories[c.title] = c.subcategories;
});
console.log(categories);
如您所见,我定义了一个接口(interface)。然后我用包含标题及其子类别的对象创建了一个时间数组。之后,我将该结构展平,将其变成您所需要的。
输出是:
{
"web development": ["php"],
"android development": ["java"]
}
关于javascript - 将 json 数组作为类别和子类别的新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49280129/